python的描述符(descriptor)、裝飾器(property)造成的一個(gè)無限遞歸問題分享
來源:易賢網(wǎng) 閱讀:1889 次 日期:2014-07-11 19:04:28
溫馨提示:易賢網(wǎng)小編為您整理了“python的描述符(descriptor)、裝飾器(property)造成的一個(gè)無限遞歸問題分享”,方便廣大網(wǎng)友查閱!

這篇文章主要介紹了python的描述符(descriptor)、裝飾器(property)造成的一個(gè)無限遞歸問題分享,一個(gè)不太會(huì)遇到的問題,需要的朋友可以參考下。

分享一下剛遇到的一個(gè)小問題,我有一段類似于這樣的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è)無限遞歸:

代碼如下:

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

通過多方查找后發(fā)現(xiàn)是property裝飾器的問題,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)用戶訪問._value時(shí),拋出了AttributeError從而調(diào)用了__getattr__方法去嘗試獲取。這樣程序就變成了無限遞歸。

這個(gè)問題看上去不復(fù)雜,但是當(dāng)你的_value方法是比較隱晦的拋出AttributeError的話,調(diào)試起來就會(huì)比較困難了。

更多信息請(qǐng)查看IT技術(shù)專欄

更多信息請(qǐng)查看腳本欄目
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國考·省考課程試聽報(bào)名

  • 報(bào)班類型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺(tái) | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)