Suppose I want to run the following code using Python 3.6.3:
class Foo:
def bar(self):
return 1
def __len__(self):
return 2
class FooWrapper:
def __init__(self, foo):
self.bar = foo.bar
self.__len__ = foo.__len__
f = Foo()
print(f.bar())
print(f.__len__())
print(len(f))
w = FooWrapper(Foo())
print(w.bar())
print(w.__len__())
print(len(w))
Here's the output:
1
2
2
1
2
TypeError: object of type 'FooWrapper' has no len()
So __len__()
works, but len()
does not? What gives and how go I properly copy __len__
method from Foo
to FooWrapper
?
By the way, the following behavior is universal for all 'special' methods, not only __len__
: for example, __iter__
or __getitem__
do not work either (unless called directly)