python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1655字,纯文字阅读大概需要3分钟。
内容图文
![python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享](/upload/InfoBanner/zyjiaocheng/433/8deb248b34a0411aa1acdbfd5a125721.jpg)
# 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)造成的一个无限递归问题分享全部内容,希望文章能够帮你解决python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。