python(第五天):__getattr__ 和 __getattribute__

本文详细探讨了Python中__getattr__与__getattribute__这两个特殊方法的区别及工作原理。__getattr__在查找属性未果时被调用,而__getattribute__则在每次属性访问时都会被触发。文章还通过示例代码展示了这两种方法的具体使用场景。

This chapter I plan to write by English. 如果有什么错误欢迎指正.

I will talk about the difference between __getattr__(self,name)  and __getattribute__(self,name)

Firstly look at the description of __getattr__:

Called when an attribute lookup has not found the attribute in the usual places(i.e. it is not an instance attribute nor is it found in the class tree for self).

arguments:name is the attribute name

This method should return the (computed) attribute value or raise an AttributeErrorexception.

就是说如果在实例的搜索树中没有找到这个属性就调用__getattr__(self,name)

这里要注意一点私有成员的实现方式是_ClassName__attributeName所以当调用__attributeName时也会触发__getattri__.


look at the description of  __getattribute__:

Called unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(),the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError.

无条件被调用,通过实例访问属性。如果class中定义了__getattr__(),则__getattr__()不会被调用(除非显示调用或引发AttributeError异常)


    def __getattribute__(self, *args, **kwargs): 
        print("__getattribute__() is called") 
#         return object.__getattribute__(self, *args, **kwargs) 
        raise AttributeError
    def __getattr__(self, name): 
        print("__getattr__() is called ") 
        return name + " from getattr"

如果在上面的代码中 没有 raise AttributeError则不会触发__getattr__
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值