python中__get__,__getattr__,__getattribute__的區別

來源:互聯網
上載者:User

標籤:調用   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__的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.