python中__get__,__getattr__,__getattribute__的區別

__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的一個屬性被調用) 函數

 1 class C(object):
 2     a = 'abc'
 3     def __getattribute__(self, *args, **kwargs):
 4         print("__getattribute__() is called")
 5         return object.__getattribute__(self, *args, **kwargs)
 6 #        return "haha"
 7     def __getattr__(self, name):
 8         print("__getattr__() is called ")
 9         return name + " from getattr"
10     
11     def __get__(self, instance, owner):
12         print("__get__() is called", instance, owner)
13         return self
14     
15     def foo(self, x):
16         print(x)
17 
18 class C2(object):
19     d = C()
20 if __name__ == '__main__':
21     c = C()
22     c2 = C2()
23     print(c.a)
24     print(c.zzzzzzzz)
25     c2.d
26     print(c2.d.a)

輸出結果是:spa

1 __getattribute__() is called  
2 abc  
3 __getattribute__() is called  
4 __getattr__() is called   
5 zzzzzzzz from getattr  
6 __get__() is called <__main__.C2 object at 0x16d2310> <class '__main__.C2'>  
7 __get__() is called <__main__.C2 object at 0x16d2310> <class '__main__.C2'>  
8 __getattribute__() is called  
9 abc  


小結:能夠看出,每次經過實例訪問屬性,都會通過__getattribute__函數。而當屬性不存在時,仍然須要訪問__getattribute__,不過接着要訪問__getattr__。這就好像是一個異常處理函數。 
每次訪問descriptor(即實現了__get__的類),都會先通過__get__函數。 

須要注意的是,當使用類訪問不存在的變量是,不會通過__getattr__函數。而descriptor不存在此問題,只是把instance標識爲none而已。code

相關文章
相關標籤/搜索