__get__,__getattr__和__getattribute都是会见属性的要领,但不太沟通。
object.__getattr__(self, name)
当一般位置找不到attribute的时候,会挪用getattr,返回一个值或AttributeError异常。
object.__getattribute__(self, name)
无条件被挪用,通过实例会见属性。假如class中界说了__getattr__(),则__getattr__()不会被挪用(除非显示挪用或激发AttributeError异常)
object.__get__(self, instance, owner)
只用在descriptor中。可以通过owner class可能instance来会见属性。
class C(object): a = 'abc' def __getattribute__(self, *args, **kwargs): print("__getattribute__() is called") return object.__getattribute__(self, *args, **kwargs) # return "haha" def __getattr__(self, name): print("__getattr__() is called ") return name + " from getattr" def __get__(self, instance, owner): print("__get__() is called", instance, owner) return self def foo(self, x): print(x) class C2(object): d = C() if __name__ == '__main__': c = C() c2 = C2() print(c.a) print(c.zzzzzzzz) c2.d print(c2.d.a)
输出功效是:
__getattribute__() is called
abc
__getattribute__() is called
__getattr__() is called
zzzzzzzz from getattr
__get__() is called <__main__.C2 object at 0x16d2310> <class '__main__.C2'>
__get__() is called <__main__.C2 object at 0x16d2310> <class '__main__.C2'>
__getattribute__() is called
abc
小结:可以看出,每次通过实例会见属性,城市颠末__getattribute__函数。而当属性不存在时,仍然需要会见__getattribute__,不外接着要会见__getattr__。这就仿佛是一个异常处理惩罚函数。
每次会见descriptor(即实现了__get__的类),城市先颠末__get__函数。
需要留意的是,当利用类会见不存在的变量是,不会颠末__getattr__函数。而descriptor不存在此问题,只是把instance标识为none罢了。