python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享

yipeiwu_com6年前Python基础

分享一下刚遇到的一个小问题,我有一段类似于这样的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 实现批量xls文件转csv文件的方法

引言:以前写的一个批量xls转csv的python简单脚本,用的是python2.7 #coding=utf-8 import os import time import loggi...

Python+OpenCV让电脑帮你玩微信跳一跳

Python+OpenCV让电脑帮你玩微信跳一跳

前言 最近微信小游戏跳一跳大热,自己也是中毒颇久,无奈手残最高分只拿到200分。无意间看到教你用Python来玩微信跳一跳一文,在电脑上利用adb驱动工具操作手机,详细的介绍以及如何安装...

对python中的os.getpid()和os.fork()函数详解

如下所示: import os import sys import time processNmae = 'parent' print "Program executing...

用Python实现随机森林算法的示例

拥有高方差使得决策树(secision tress)在处理特定训练数据集时其结果显得相对脆弱。bagging(bootstrap aggregating 的缩写)算法从训练数据的样本中建...

让你Python到很爽的加速递归函数的装饰器

今天我们会讲到一个[装饰器] 注记:链接“装饰器”指Python3教程中的装饰器教程。可以在这里快速了解什么是装饰器。 @functools.lru_cache——进行函数执行结果备忘,...