国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python的描述符(descriptor)、裝飾器(property)造成的一個無限遞歸問題分享

2019-11-25 18:20:10
字體:
來源:轉載
供稿:網友

分享一下剛遇到的一個小問題,我有一段類似于這樣的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的話,調試起來就會比較困難了。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大宁县| 深水埗区| 济南市| 昌乐县| 蓝田县| 芜湖县| 木兰县| 星子县| 手游| 烟台市| 开江县| 刚察县| 东山县| 宜章县| 嘉禾县| 铜山县| 行唐县| 武山县| 嵩明县| 锡林郭勒盟| 马关县| 通州区| 东阳市| 洞口县| 屏边| 宝山区| 东乡县| 汉寿县| 遂宁市| 桃园市| 广河县| 新源县| 三江| 洱源县| 汤阴县| 长治市| 黄梅县| 谢通门县| 敦化市| 进贤县| 根河市|