標籤:調用 tor attribute 變數 def 自己 zha self pytho
__get__,__getattr__和__getattribute都是訪問屬性的方法,但不太相同。
object.__getattr__(self, name)
當一般位置找不到attribute的時候,會調用getattr,返回一個值或AttributeError異常。
object.__getattribute__(self, name)
無條件被調用,通過執行個體訪問屬性。如果class中定義了__getattr__(),則__getattr__()不會被調用(除非顯示調用或引發AttributeError異常)
object.__get__(self, instance, owner)
如果class定義了它,則這個class就可以稱為descriptor。owner是所有者的類,instance是訪問descriptor的執行個體,如果不是通過執行個體訪問,而是通過類訪問的話,instance則為None。(descriptor的執行個體自己訪問自己是不會觸發__get__,而會觸發__call__,只有descriptor作為其它類的屬性才有意義。)(所以下文的d是作為C2的一個屬性被調用)
class C(object): a = ‘abc‘def __getattribute__(self, name): print("__getattribute__() is called"),name return object.__getattribute__(self, name) def __getattr__(self, name): print("__getattr__() is called "),name 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) print ‘==============1‘ C2.d print ‘==============2‘ print(c2.d.a)
結果
__getattribute__() is called aabc__getattribute__() is called zzzzzzzz__getattr__() is called zzzzzzzzzzzzzzzz from getattr==============1(‘__get__() is called‘, None, <class ‘__main__.C2‘>)==============2(‘__get__() is called‘, <__main__.C2 object at 0x00000000030BCDA0>, <class ‘__main__.C2‘>)__getattribute__() is called aabc
小結:可以看出,每次通過執行個體訪問屬性,都會經過__getattribute__函數。而當屬性不存在時,仍然需要訪問__getattribute__,不過接著要訪問__getattr__。這就好像是一個異常處理函數。
每次訪問descriptor(即實現了__get__的類),都會先經過__get__函數。
需要注意的是,當使用類訪問不存在的變數是,不會經過__getattr__函數。而descriptor不存在此問題,只是把instance標識為none而已。
參考:http://luozhaoyu.iteye.com/blog/1506426
python中__get__,__getattr__,__getattribute__的區別