data attributes override method attributes?
Ian Kelly
ian.g.kelly at gmail.com
Fri Sep 28 14:25:11 EDT 2012
More information about the Python-list mailing list
Fri Sep 28 14:25:11 EDT 2012
- Previous message (by thread): data attributes override method attributes?
- Next message (by thread): data attributes override method attributes?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Fri, Sep 28, 2012 at 12:02 PM, Prasad, Ramit <ramit.prasad at 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.
- Previous message (by thread): data attributes override method attributes?
- Next message (by thread): data attributes override method attributes?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list