On Fri, Sep 28, 2012 at 12:02 PM, Prasad, Ramit
<ramit.pra...@jpmorgan.com> wrote:
> Just to make sure I am following, if you call
> foo.__len__() it goes to the instance code while
> if you do len(foo) it will go to class.__len__()?

Yes:

>>> class Foo(object):
...     def __len__(self):
...         return 42
...
>>> foo = Foo()
>>> foo.__len__ = lambda: 43
>>> foo.__len__()
43
>>> len(foo)
42

> If so, why?

In the first case, "foo.__len__" just does the normal attribute lookup
for the class.  Instance attributes shadow class attributes, so the
instance attribute is returned and then called.

In the second case, "len(foo)" is implemented by a method in a
prescribed location:  foo.__class__.__len__.  It only looks in the
class for efficiency and because that is what the class object is for:
to define how its instances behave.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to