猫游记蓝宝书,搜索引擎原理,依依情人网
分享一下刚遇到的一个小问题,我有一段类似于这样的python代码:
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
这行的注释去掉的话,即在_value方法里面抛出attributeerror异常,事情就会变得有些奇怪。程序运行的时候并不会抛出异常,而是会进入一个无限递归:
通过多方查找后发现是property装饰器的问题,property实际上是一个descriptor。在python doc中可以发现这样的文字:
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爬虫:Request Payload和Form Data的简单区别说明
浅谈Python中threading join和setDaemon用法及区别说明
Python3-异步进程回调函数(callback())介绍
python继承threading.Thread实现有返回值的子类实例
Python中使用threading.Event协调线程的运行详解
网友评论