• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享

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

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

分享一下刚遇到的一个小问题,我有一段类似于这样的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
</div>
运行后可以得到正确的结果
__getattr__: v
This is a test.</div>
但是注意,如果把
#        raise AttributeError("test")</div>


这行的注释去掉的话,即在_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</div>

通过多方查找后发现是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.
</div>

这样当用户访问._value时,抛出了AttributeError从而调用了__getattr__方法去尝试获取。这样程序就变成了无限递归。

这个问题看上去不复杂,但是当你的_value方法是比较隐晦的抛出AttributeError的话,调试起来就会比较困难了。

</div>

您可能想查找下面的文章:

相关文章

  • 从Python程序中访问Java类的简单示例
  • 利用Python绘制数据的瀑布图的教程
  • Python获取Linux系统下的本机IP地址代码分享
  • 利用PyInstaller将python程序.py转为.exe的方法详解
  • Python实现的ini文件操作类分享
  • Python HTTP客户端自定义Cookie实现实例
  • python中字典(Dictionary)用法实例详解
  • python实现文件快照加密保护的方法
  • Python Web框架Pylons中使用MongoDB的例子
  • Python和JavaScript间代码转换的4个工具

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • python中__call__内置函数用法实例
    • 浅析Python中元祖、列表和字典的区别
    • python将文本转换成图片输出的方法
    • python的tkinter布局之简单的聊天窗口实现方法
    • Python统计日志中每个IP出现次数的方法
    • Python之Web框架Django项目搭建全过程
    • Python统计列表中的重复项出现的次数的方法
    • python开发之list操作实例分析
    • 用Python实现协同过滤的教程
    • python获取远程图片大小和尺寸的方法

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有