yonayaha
yonayaha

Reputation: 77

python __getattr__ doesn't work for built-in functions

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:

  1. What in those functions implementation is causing the different behavior.

  2. How can I bring Var class to work with len as well.

Upvotes: 4

Views: 955

Answers (1)

pawelbylina
pawelbylina

Reputation: 1485

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__()?

Upvotes: 2

Related Questions