__getattribute__

__getattribute__

__getattribute__介绍

1.先看看:__getattr__

  • 点 . 属性 没找到触发

    class Foo:
        def __init__(self, x):
            self.x = x
    
        def __getattr__(self, item):
            print("没找到,所以回执行我")
    
    
    f1 = Foo(10)
    print(f1.x)  # 10
    f1.xxxxxx  # 不存在的属性访问,触发__getattr__
    

2.__getattribute__

  • 点 . 属性 无论找没找到都触发

    class Foo:
        def __init__(self, x):
            self.x = x
    
        def __getattribute__(self, item):
            print("不管是否存在,我都会执行")
    
    
    f1 = Foo(100)
    f1.x  # 不管是否存在,我都会执行
    f1.xxxx  # 不管是否存在,我都会执行
    

3.__getattr____getattribute__同时存在

#两者同时存在
class Bar:
    def __init__(self, name):
        self.name = name

    def __getattr__(self, item):
        print("没找到,触发了我")

    def __getattribute__(self, item):
        print(f"无论找没找到,都触发了我--》{item}")


ll = Bar("淘小欣")
ll.name  # 无论找没找到,都触发了我--》name
ll.age  # 无论找没找到,都触发了我--》age


#s设置异常
class Bar:
    def __init__(self, name):
        self.name = name

    def __getattr__(self, item):
        print("没找到,触发了我")

    def __getattribute__(self, item):
        print(f"无论找没找到,都触发了我==>{item}")
        raise AttributeError("让小弟接管")  # 设置异常,直接交给__getattr__


bb = Bar("淘小欣")

bb.name
'''输出内容
无论找没找到,都触发了我==>name
没找到,触发了我
'''

bb.age

'''输出内容
无论找没找到,都触发了我==>age
没找到,触发了我
'''
  • [对象] . [属性] 的调用顺序 : 先执行 __getattribute__—>去类的名称空间找—>__getattr__(本质是去对象自己的名称空间找)
  • [对象] . [属性] 的查找顺序 : 对象自己**—>—>父类—>**父类

4.总结

  • __getattribute__方法优先级比__getattr__
  • 没有重写__getattribute__的情况下, 默认使用的是父类的__getattribute__方法
  • 只有在使用默认__getattribute__方法中找不到对应的属性时,才会调用__getattr__
  • 如果是对不存在的属性做处理,尽量把逻辑写在__getattr__方法中
  • 如果非得重写__getattribute__方法,需要注意两点:
    • 第一是避免.操作带来的死循环
    • 第二是不要遗忘父类的__getattribute__方法在子类中起的作用
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贾维斯Echo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值