python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享
2019/7/13 21:49:35
本文主要是介绍python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
分享一下刚遇到的一个小问题,我有一段类似于这样的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的话,调试起来就会比较困难了。
这篇关于python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础
- 2024-09-2610 种方法写出更好的 Python 代码
- 2024-09-25Python编程基础详解
- 2024-09-25Python编程入门教程
- 2024-09-25从零开始使用Python构建LLaMA 3
- 2024-09-23Python中理解和使用树形结构的简单教程
- 2024-09-23Python 编程基础入门
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战