__getattr__ in python

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值