日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

python的描述符(descriptor)、裝飾器(property)造成

系統 1854 0

分享一下剛遇到的一個小問題,我有一段類似于這樣的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


運行后可以得到正確的結果
復制代碼 代碼如下:

__getattr__: v
This is a test.

但是注意,如果把
復制代碼 代碼如下:

#??????? raise AttributeError("test")


這行的注釋去掉的話,即在_value方法里面拋出AttributeError異常,事情就會變得有些奇怪。程序運行的時候并不會拋出異常,而是會進入一個無限遞歸:

復制代碼 代碼如下:

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

通過多方查找后發現是property裝飾器的問題,property實際上是一個descriptor。在python doc中可以發現這樣的文字:

復制代碼 代碼如下:

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.

這樣當用戶訪問._value時,拋出了AttributeError從而調用了__getattr__方法去嘗試獲取。這樣程序就變成了無限遞歸。

這個問題看上去不復雜,但是當你的_value方法是比較隱晦的拋出AttributeError的話,調試起來就會比較困難了。


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 剑阁县| 漳平市| 嘉鱼县| 奉节县| 天长市| 九龙城区| 新野县| 金塔县| 德清县| 青冈县| 延川县| 砀山县| 家居| 雷州市| 德钦县| 永川市| 高雄县| 崇明县| 衡东县| 阿勒泰市| 稻城县| 宾川县| 河北区| 宁化县| 通山县| 谢通门县| 扎兰屯市| 尉氏县| 额尔古纳市| 金阳县| 梓潼县| 修武县| 叶城县| 凤台县| 电白县| 宁阳县| 泰和县| 佛坪县| 安徽省| 兴山县| 曲麻莱县|