對比Python中__getattr__和 __getattribute__獲取屬性的用法
相信大家覺得大多數(shù)時候我們并不太需要關(guān)注getattribute和getattr的一些細(xì)節(jié)(至少我自己吧:)),
一般情況下消費(fèi)我們自定義的類的時候,我們對類的結(jié)構(gòu)都了解,不會刻意偏離,造成一些屬性訪問的錯誤。
不過作為一個有好奇心有追求有氣質(zhì)的python寶寶,怎么可能不稍稍研究一下呢。好吧,其實(shí)是在github上讀到一個開源項(xiàng)目sinaweibopy的源碼才看的,代碼挺有意思,正好當(dāng)作一個實(shí)用的例子,來看看如何自定義實(shí)現(xiàn)gettattr讓代碼更加的動態(tài)優(yōu)雅:
# 例子在原來的基礎(chǔ)上簡化了一下,排除依賴和干擾,詳細(xì)參見原項(xiàng)目 class UrlGenerator(object): def __init__(self, root_url): self.url = root_url def __getattr__(self, item): if item == 'get' or item == 'post': print self.url return UrlGenerator('{}/{}'.format(self.url, item)) url_gen = UrlGenerator('http://xxxx') url_gen.users.show.get >>> http://xxxx/users/show
充分利用getattr會在沒有查找到相應(yīng)實(shí)例屬性時被調(diào)用的特點(diǎn),方便的通過鏈?zhǔn)秸{(diào)用生成對應(yīng)的url,源代碼中在碰到http method的時候返回一個
可調(diào)用的對象更加的優(yōu)雅,鏈?zhǔn)降牟僮鞑粌H優(yōu)雅而且還能很好的說明調(diào)用的接口的意義(restful的接口啦)。
示例
1.__getattr__示例:
class Test(object): def __init__(self,name): self.name = name def __getattr__(self, value): if value == 'address': return 'China' if __name__=="__main__": test = Test('letian') print test.name print test.address test.address = 'Anhui' print test.address
運(yùn)行結(jié)果:
letian China Anhui
如果是調(diào)用了一個類中未定義的方法,則__getattr__也要返回一個方法,例如:
class Test(object): def __init__(self,name): self.name = name def __getattr__(self, value): return len if __name__=="__main__": test = Test('letian') print test.getlength('letian')
運(yùn)行結(jié)果:
6
2.__getattribute__示例:
class Test(object): def __init__(self,name): self.name = name def __getattribute__(self, value): if value == 'address': return 'China' if __name__=="__main__": test = Test('letian') print test.name print test.address test.address = 'Anhui' print test.address
運(yùn)行結(jié)果:
None China China
深入思考
既然能通過定制類的getattr自定義方法來實(shí)現(xiàn)一些優(yōu)雅的功能,自然我們也要對它有一些了解,包括和它相似的自定義方法getattribute
1. 用作實(shí)例屬性的獲取和攔截
當(dāng)訪問某個實(shí)例屬性時, getattribute會被無條件調(diào)用,如未實(shí)現(xiàn)自己的getattr方法,會拋出AttributeError提示找不到這個屬性,如果自定義了自己getattr方法的話,方法會在這種找不到屬性的情況下被調(diào)用,比如上面的例子中的情況。所以在找不到屬性的情況下通過實(shí)現(xiàn)自定義的getattr方法來實(shí)現(xiàn)一些功能是一個不錯的方式,因?yàn)樗粫駁etattribute方法每次都會調(diào)用可能會影響一些正常情況下的屬性訪問:
class Test(object): def __init__(self, p): self.p = p def __getattr__(self, item): return 'default' t = Test('p1') print t.p print t.p2 >>> p1 >>> default
2. 自定義getattribute的時候防止無限遞歸
因?yàn)間etattribute在訪問屬性的時候一直會被調(diào)用,自定義的getattribute方法里面同時需要返回相應(yīng)的屬性,通過self.__dict__取值會繼續(xù)向下調(diào)用getattribute,造成循環(huán)調(diào)用:
class AboutAttr(object): def __init__(self, name): self.name = name def __getattribute__(self, item): try: return super(AboutAttr, self).__getattribute__(item) except KeyError: return 'default'
這里通過調(diào)用綁定的super對象來獲取隊形的屬性,對新式類來說其實(shí)和object.__getattribute__(self, item)一樣的道理:
默認(rèn)情況下自定義的類會從object繼承g(shù)etattribute方法,對于屬性的查找是完全能用的
getattribute的實(shí)現(xiàn)感覺還是挺抽象化的,只需要綁定相應(yīng)的實(shí)例對象和要查找的屬性名稱就行
3.同時覆蓋掉getattribute和getattr的時候,在getattribute中需要模仿原本的行為拋出AttributeError或者手動調(diào)用getattr
class AboutAttr(object): def __init__(self, name): self.name = name def __getattribute__(self, item): try: return super(AboutAttr, self).__getattribute__(item) except KeyError: return 'default' except AttributeError as ex: print ex def __getattr__(self, item): return 'default' at = AboutAttr('test') print at.name print at.not_exised >>>test >>>'AboutAttr' object has no attribute 'not_exised' >>>None
上面例子里面的getattr方法根本不會被調(diào)用,因?yàn)樵镜腁ttributeError被我們自行處理并未拋出,也沒有手動調(diào)用getattr,所以訪問not_existed的結(jié)果是None而不是default.
相關(guān)文章
python 如何將帶小數(shù)的浮點(diǎn)型字符串轉(zhuǎn)換為整數(shù)
在python中如何實(shí)現(xiàn)將帶小數(shù)的浮點(diǎn)型字符串轉(zhuǎn)換為整數(shù)呢?今天小編就為大家介紹一下解決方案,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05Python+PyQt5實(shí)現(xiàn)開發(fā)Memcached客戶端
這篇文章主要介紹了如何使用Python和PyQt5來制作一個Memcached客戶端,以便我們可以輕松地與Memcached服務(wù)器進(jìn)行交互,感興趣的小伙伴可以了解一下2023-06-06Python實(shí)現(xiàn)的密碼強(qiáng)度檢測器示例
這篇文章主要介紹了Python實(shí)現(xiàn)的密碼強(qiáng)度檢測器,結(jié)合實(shí)例形式分析了Python密碼強(qiáng)度檢測的原理與實(shí)現(xiàn)方法,涉及Python字符串運(yùn)算與轉(zhuǎn)換、判斷等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08解決pycharm每次打開項(xiàng)目都需要配置解釋器和安裝庫問題
最近在使用pycharm開發(fā)新項(xiàng)目的時候,每次打開新的工程都顯示沒有解釋器,要不加了解釋器就是代碼一堆沒有紅色錯誤提示沒有模塊問題,很多朋友都遇到過這種情況,現(xiàn)小編把解決方法分享到腳本之家平臺,需要的朋友一起看看吧2020-02-02python通過SSH登陸linux并操作的實(shí)現(xiàn)
這篇文章主要介紹了python通過SSH登陸linux并操作的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10