• 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使用正则搜索字符串或文件中的浮点数代码实例
  • 详细解析Python当中的数据类型和变量
  • Python中的模块导入和读取键盘输入的方法
  • python使用PyGame播放Midi和Mp3文件的方法
  • 一些Python中的二维数组的操作方法
  • Python正则表达式教程之一:基础篇
  • Python import自定义模块方法
  • Python3基础之基本运算符概述
  • Python map和reduce函数用法示例
  • 详解Python中的变量及其命名和打印

文章分类

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

最近更新的内容

    • Python的__builtin__模块中的一些要点知识
    • Python抓取电影天堂电影信息的代码
    • 更改Ubuntu默认python版本的两种方法python-> Anaconda
    • python 链接和操作 memcache方法
    • Python中使用tarfile压缩、解压tar归档文件示例
    • python在windows命令行下输出彩色文字的方法
    • python类和继承用法实例
    • 简单介绍Python中的floor()方法
    • Python实现的Kmeans++算法实例
    • Python字符和字符值(ASCII或Unicode码值)转换方法

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

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