【1.122】 学习 getattribute

看看前面的  getattr-------  在访问不存在的属性 时   

就会 执行 内置函数 ——getattr———

class Foo:
    def __init__(self,x):
        self.x = x
    def __getattr__(self, item):
        print("属性不存在就会执行")

f1 = Foo(10)
print(f1.__dict__)
print(f1.x)
print(f1.xx)
看看 getattr
class Foo:
    def __init__(self,x):
        self.x=x

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

f1=Foo(10)
f1.x
f1.xxxxxx
不管是否存在都会执行__getattribute__
同时存在,看看如何运行


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

#当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError

 

posted @ 2016-06-12 22:15  科学小怪癖  阅读(65)  评论(0)    收藏  举报