网站首页  汉语字词  英语词汇  考试资料  写作素材

请输入您要查询的考试资料:

 

  • 华东师范大学2017年硕士研究生招生考试科目初试范围(汉语国际教育)
  • 华东师范大学2017年硕士研究生招生考试科目初试范围(体育教学)
  • 华东师范大学2017年硕士研究生招生考试科目初试范围(民族传统体育学)
  • 华东师范大学2017年硕士研究生招生考试科目初试范围(体育教育训练学)
  • 华东师范大学2017年硕士研究生招生考试科目初试范围(运动人体科学)
  • 北京农学院2018年初试科目(702)植物生理学考试大纲
  • 华东师范大学2017年硕士研究生招生考试科目初试范围(体育人文社会学)
  • 北京联合大学2018年推免招收硕士研究生招生章程
  • 2018年山东农业大学研招10问10答
  • 中华女子学院2018年硕士研究生招生考试报考须知
  • 山东农业大学2018年接收推荐免试硕士研究生章程
  • 中华女子学院2018年社会工作硕士专业学位研究生招生简章
  • remaining participant
  • remaining portion
  • remaining prisoners
  • remaining quarter
  • remaining survivors
  • remains
  • remains-to-be-seen
  • remake
  • remaking
  • remand
  • 雨露
  • 雨靴
  • 雨鞋
  • 雪上加霜
  • 雪上芭蕾
  • 雪上运动
  • 雪中送炭
  • 雪乡
  • 房屋租赁合同税金该由谁缴纳
  • 口头房屋租赁合同有用吗?
  • 公司羊年春节演讲稿
  • 公司年终新春演讲稿
  • 2014我的中国梦主题活动总结
  • 2014志愿者服务活动总结
  • 乡镇统计员工作总结
  • 生产统计员工作总结
  • 办公室新人文秘工作总结
  • 事业单位秘书年度个人工作总结
  • 标题 python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享
    分类 范文、应用文-IT技术专栏-脚本栏目
    内容
        这篇文章主要介绍了python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享,一个不太会遇到的问题,需要的朋友可以参考下。
        分享一下刚遇到的一个小问题,我有一段类似于这样的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的话,调试起来就会比较困难了。
    随便看

     

    客官网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

     

    Copyright © 2002-2024 cumcu.com All Rights Reserved
    更新时间:2026/6/20 12:30:12