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

yipeiwu_com5年前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装饰器计算函数运行时间的实例

装饰器在python里面有很重要的作用, 如果能够熟练使用,将会大大的提高工作效率 今天就来见识一下 python 装饰器,到底是怎么工作的。 本文主要是利用python装饰器计算函数运...

利用Python实现在同一网络中的本地文件共享方法

本文利用Python3启动简单的HTTP服务器,以实现在同一网络中共享本地文件。 启动HTTP服务器 打开终端,转入目标文件所在文件夹,键入以下命令: $ cd /Users/zer...

利用pytorch实现对CIFAR-10数据集的分类

步骤如下: 1.使用torchvision加载并预处理CIFAR-10数据集、 2.定义网络 3.定义损失函数和优化器 4.训练网络并更新网络参数 5.测试网络 运行环境: win...

Flask入门教程实例:搭建一个静态博客

Flask入门教程实例:搭建一个静态博客

现在流行的静态博客/网站生成工具有很多,比如 Jekyll, Pelican, Middleman, Hyde 等等,StaticGen 列出了目前最流行的一些静态网站生成工具。 我们的...

python函数返回多个值的示例方法

python可以返回多个值,确实挺方便函数里的return只能返回一个值,但是返回类型是没是限制的因此,我们可以“返回一个 tuple类型,来间接达到返回多个值”。例子是我在robot...