__getattr__ and __getattribute__
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Tue May 8 19:08:33 EDT 2007
En Tue, 08 May 2007 08:22:03 -0300, km <srikrishnamohan at gmail.com>
escribió:
> i find it difficult to understand the difference between the magic
> methods
> __getattr__ and __getattribute__
> and so donot know when to use former or later.
> can someone brief me on it ?
This is better understood with a bit of history.
On earlier Python versions (before 2.2) the only object model available
was what we now call "classic classes".
Classic instances hold their attributes in a dictionary, called __dict__.
Attribute lookup starts at this instance dictionary; if not found,
continues in the class, and its parent class, all along the inheritance
tree. If still not found, __getattr__ (if it exists) is called, and should
return the attribute value or raise AttributeError. That is, __getattr__
is called *last*, and *only* when the attribute was not previously found
in the usual places.
Since Python 2.2, there are "new style classes" available; they inherit
directly or indirectly from object. A new style instance may not even have
a __dict__. An existing __getattribute__ method is tried *first*; it
should return the attribute value or raise AttributeError. If no custom
__getattribute__ exists, the default object.__getattribute__ is used. As a
last resort, if __getattr__ is defined, it is called.
OTOH, there is a single version of __setattr__, which is always invoked
when setting an attribute.
--
Gabriel Genellina
More information about the Python-list
mailing list