python - getattr 的最大递归深度错误

标签 python exception recursion descriptor

我有这个代码;

class NumberDescriptor(object):
    def __get__(self, instance, owner):
        name = (hasattr(self, "name") and self.name)
        if not name:
            name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0]
            self.name = name
        return getattr(instance, '_' + name)
    def __set__(self,instance, value):
        name = (hasattr(self, "name") and self.name)
        if not name:
            owner = type(instance)
            name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0]
            self.name = name
        setattr(instance, '_' + name, int(value))

class Insan(object):
    yas = NumberDescriptor()

a = Insan()
print a.yas
a.yas = "osman"
print a.yas

我在行 name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0] 中遇到最大递归深度错误。我希望该行获取用于当前描述符实例的变量名称。谁能看出我在这里做错了什么?

最佳答案

getattr() 调用正在调用您的 __get__

解决此问题的一种方法是显式调用父类(super class) object:

object.__getattribute__(instance, name)

或者,更清楚:

instance.__dict__[name]

关于python - getattr 的最大递归深度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12163476/

相关文章:

python - 对数组进行排序并将索引追溯到其排序顺序

python - PyQt app.exec() 似乎是非阻塞的

recursion - F# - 匿名记录的递归

python - Linux 上的 xlwings 替代方案

python - numpy 结构化数组的数组数学

java - Junit 测试 Map<String, List<String>> 的 java.lang.NullPointerException

c - 如何在 Linux 上用 C 递归列出目录?

Jquery递归比较两个元素的html和属性

java - Hibernate 和 Apache Tomcat 的问题

spring - 在tomcat 7.0 + spring MVC中使用Tomcat manager,Webapp reload报apachelifecycle异常