python的描述符(descriptor)、裝飾器(property)造成的一個(gè)無(wú)限遞歸問(wèn)題分享
分享一下剛遇到的一個(gè)小問(wèn)題,我有一段類似于這樣的python代碼:
# coding: utf-8
class A(object):
@property
def _value(self):
# raise AttributeError("test")
return {"v": "This is a test."}
def __getattr__(self, key):
print "__getattr__:", key
return self._value[key]
if __name__ == '__main__':
a = A()
print a.v
運(yùn)行后可以得到正確的結(jié)果
__getattr__: v
This is a test.
但是注意,如果把
# raise AttributeError("test")
這行的注釋去掉的話,即在_value方法里面拋出AttributeError異常,事情就會(huì)變得有些奇怪。程序運(yùn)行的時(shí)候并不會(huì)拋出異常,而是會(huì)進(jìn)入一個(gè)無(wú)限遞歸:
File "attr_test.py", line 12, in __getattr__
return self._value[key]
File "attr_test.py", line 12, in __getattr__
return self._value[key]
RuntimeError: maximum recursion depth exceeded while calling a Python object
通過(guò)多方查找后發(fā)現(xiàn)是property裝飾器的問(wèn)題,property實(shí)際上是一個(gè)descriptor。在python doc中可以發(fā)現(xiàn)這樣的文字:
object.__get__(self, instance, owner)
Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). owner is always the owner class, while instance is the instance that the attribute was accessed through, or None when the attribute is accessed through the owner. This method should return the (computed) attribute value or raise an AttributeError exception.
這樣當(dāng)用戶訪問(wèn)._value時(shí),拋出了AttributeError從而調(diào)用了__getattr__方法去嘗試獲取。這樣程序就變成了無(wú)限遞歸。
這個(gè)問(wèn)題看上去不復(fù)雜,但是當(dāng)你的_value方法是比較隱晦的拋出AttributeError的話,調(diào)試起來(lái)就會(huì)比較困難了。
相關(guān)文章
利用python實(shí)現(xiàn)平穩(wěn)時(shí)間序列的建模方式
這篇文章主要介紹了利用python實(shí)現(xiàn)平穩(wěn)時(shí)間序列的建模方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
python調(diào)用新浪微博API項(xiàng)目實(shí)踐
因?yàn)樽罱佑|到調(diào)用新浪微博開(kāi)放接口的項(xiàng)目,所以就想試試用python調(diào)用微博API,需要的朋友可以參考下2014-07-07
python編輯用戶登入界面的實(shí)現(xiàn)代碼
這篇文章主要介紹了python編輯用戶登入界面的實(shí)現(xiàn)代碼,非常不錯(cuò),代碼簡(jiǎn)單易懂,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-07-07
Pytest+Request+Allure+Jenkins實(shí)現(xiàn)接口自動(dòng)化
這篇文章介紹了Pytest+Request+Allure+Jenkins實(shí)現(xiàn)接口自動(dòng)化的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
最強(qiáng)Python可視化繪圖庫(kù)Plotly詳解用法
數(shù)據(jù)分析離不開(kāi)數(shù)據(jù)可視化。Plotly 是一款用來(lái)做數(shù)據(jù)分析和可視化的在線平臺(tái),功能非常強(qiáng)大,可以在線繪制很多圖形比如條形圖、散點(diǎn)圖、餅圖、直方圖等等2021-11-11
python 利用turtle模塊畫出沒(méi)有角的方格
今天小編就為大家分享一篇python 利用turtle模塊畫出沒(méi)有角的方格,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11

