Attribute fetch in classes and class instances:
from https://docs.python.org/2/reference/datamodel.html:
For classes
class attribute references are translated to lookups in dictionary: C.x => C.__dict__['x']
. when attribute name is not found in the dictionary, the search continues in the base classes: either depth-first, left-to-right in old-style or diamond inheritance in new-style.
For instances
Attribute search first takes place in instance. If not found in instance, the search continues with the class attributes. If no class attribute is found, __getattr__()
in object’s class will be called to deal with this situation.
To summary, __getattr__()
is only called in instance attribute search and only in condition when there is no such attribute available in both instance or parent classes.
Also, the rule of __getattr__()
is different between old-style and new style.
In new style classes:
1. built-in operations for __X__()
operator overloading methods - the search starts begin in classes instead of instances.
2. this means those built-in operations will not be routed to __getattr__()
.
3. explicit fetch of attribute from instances still be routed to __getattr__()
.
class A:
data = 'spam'
def __getattr__(self, name):
print(name)
return getattr(self.data, name)
class B(object):
data = 'spam'
def __getattr__(self, name):
print(name)
return getattr(self.data, name)
if __name__ == '__main__':
a = A()
print(a[1])
b = B()
print(b[1])
result:
# python2 newstyle.py
__getitem__
p
Traceback (most recent call last):
File "newstyle.py", line 17, in <module>
print(b[1])
TypeError: 'B' object does not support indexing