I'm trying to build some kind of generic wrapper class to hold variable objects.
class Var:
def __init__(self, obj=None):
self.obj=obj
def __getattr__(self, attr):
return getattr(self.obj, attr)
Now for example, when I try to use it with list as obj, I get different behavior when calling __len__ attribute or len built-in function.
v1 = Var([1,2,3])
print(v1.__len__())
# output: 3
print(len(v1))
# output: TypeError: object of type 'Var' has no len()
That happens with other built-in functions as well. My questions are:
What in those functions implementation is causing the different behavior.
How can I bring Var class to work with len as well.
You have to implement your own __len__ method inside Var class. Something like this:
class Var:
def __init__(self, obj=None):
self.obj=obj
def __getattr__(self, attr):
return getattr(self.obj, attr)
def __len__(self):
return len(self.obj)
v1 = Var([1,2,3])
print(v1.__len__())
print(len(v1))
output:
pawel@pawel-XPS-15-9570:~/test$ python len.py
3
3
And here you have some information about differences between len() and __len__: Difference between len() and .__len__()?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With