data attributes override method attributes?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Sep 28 23:20:19 EDT 2012
On Fri, 28 Sep 2012 18:02:04 +0000, Prasad, Ramit 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__()?
If you call foo.__len__, the attribute lookup of __len__ will use the
exact same search path as foo.spam would use:
1) does __getattribute__ exist and intercept the call?
2) if not, does a instance attribute exist?
3) if not, does a class attribute exist?
4) if not, does a superclass attribute exist?
5) if not, does __getattr__ exist and intercept the call?
Using len(foo) bypasses steps 1) and 2) as a speed optimization. For the
common case where an instance's class directly defines a __len__ method,
that saves about 10-15% of the overhead of calling a special method,
compared to old-style classes.
--
Steven
More information about the Python-list
mailing list