首页 > 其他 > 详细

\_\_getattribute\_\_

时间:2020-02-02 13:31:16      阅读:66      评论:0      收藏:0      [点我收藏+]

__getattribute__

一、__getattr__

  • 不存在的属性访问,触发__getattr__
class Foo:
    def __init__(self, x):
        self.x = x

    def __getattr__(self, item):
        print('执行的是我')
        # return self.__dict__[item]


f1 = Foo(10)
print(f1.x)
f1.xxxxxx

10

执行的是我

二、__getattribute__

  • 查找属性无论是否存在,都会执行
class Foo:
    def __init__(self, x):
        self.x = x

    def __getattribute__(self, item):
        print('不管是否存在,我都会执行')


f1 = Foo(10)
f1.x
f1.xxxxxx

不管是否存在,我都会执行

不管是否存在,我都会执行

三、__getattr__与__getattribute__

  • 当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError
class Foo:
    def __init__(self, x):
        self.x = x

    def __getattr__(self, item):
        print('执行的是我')
        # return self.__dict__[item]
    def __getattribute__(self, item):
        print('不管是否存在,我都会执行')
        raise AttributeError('哈哈')


f1 = Foo(10)
f1.x

f1.xxxxxx

不管是否存在,我都会执行
执行的是我


不管是否存在,我都会执行
执行的是我

四、总结

  1. 当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,
  2. 只要__getattribute__在执行过程中抛出异常AttributeError,两个都会被执行

\_\_getattribute\_\_

原文:https://www.cnblogs.com/randysun/p/12251646.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!