python的描述符(descriptor)、裝飾器(property)造成的一個(gè)無限遞歸問題分享
分享一下剛遇到的一個(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ì)比較困難了。
相關(guān)文章
python操作openpyxl導(dǎo)出Excel 設(shè)置單元格格式及合并處理代碼實(shí)例
這篇文章主要介紹了python操作openpyxl導(dǎo)出Excel 設(shè)置單元格格式及合并處理代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08python實(shí)現(xiàn)植物大戰(zhàn)僵尸游戲?qū)嵗a
這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)植物大戰(zhàn)僵尸游戲的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06Dephi逆向工具Dede導(dǎo)出函數(shù)名MAP導(dǎo)入到IDA中的實(shí)現(xiàn)方法
這篇文章主要介紹了Dephi逆向工具Dede導(dǎo)出函數(shù)名MAP導(dǎo)入到IDA中,通過這個(gè)腳本,我們就可以把專業(yè)dephi程序分析的結(jié)果,轉(zhuǎn)移到IDA專業(yè)逆向代碼分析的平臺(tái),實(shí)現(xiàn)聯(lián)動(dòng),需要的朋友可以參考下2022-08-08瀏覽器常用基本操作之python3+selenium4自動(dòng)化測(cè)試(基礎(chǔ)篇3)
瀏覽器常用基本操作有很多種,今天給大家介紹python3+selenium4自動(dòng)化測(cè)試的操作方法,是最最基礎(chǔ)的一篇,對(duì)python3 selenium4自動(dòng)化測(cè)試相關(guān)知識(shí)感興趣的朋友一起看看吧2021-05-05Python對(duì)字符串實(shí)現(xiàn)去重操作的方法示例
字符串去重是python中字符串操作常見的一個(gè)需求,最近在工作中就又遇到了,所以下面這篇文章主要給大家介紹了關(guān)于Python對(duì)字符串實(shí)現(xiàn)去重操作的相關(guān)資料,文中給出了詳細(xì)的介紹,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08