__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而已。