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自动化运维之IP地址处理模块详解

实用的IP地址处理模块IPy 在IP地址规划中,涉及到计算大量的IP地址,包括网段、网络掩码、广播地址、子网数、IP类型等 别担心,Ipy模块拯救你。Ipy模块可以很好的辅助我们高效的...

Flask框架学习笔记(一)安装篇(windows安装与centos安装)

Flask 依赖于两个外部库: Werkzeug  和  Jinja2  。 Werkzeug 是一个 WSGI (在 web 应用和多种服务器之间开发和部...

python实现字符串加密成纯数字

python实现字符串加密成纯数字

本文实例为大家分享了python实现字符串加密成纯数字的具体代码,供大家参考,具体内容如下 说明:  该加密算法仅仅是做一个简单的加密,安全性就不谈了,哈哈.  算法...

python实现自动化报表功能(Oracle/plsql/Excel/多线程)

python实现自动化报表功能(Oracle/plsql/Excel/多线程)

日常会有很多固定报表需要手动更新,本文将利用python实现多线程运行oracle代码,并利用xlwings包和numpy包将结果写入到指定excel模版(不改变模版内容),并自动生成带...

python删除文本中行数标签的方法

python删除文本中行数标签的方法

问题描述: 我们在网上下载或者复制别人代码的时候经常会遇到下载的代码中包含行数标签的情况。如下图: 这些代码中包含着行数如1.,2.等,如果我们想直接运行或者copy代码需要自己手动的...