【问题标题】:Maximum recursion depth error with getattrgetattr 的最大递归深度误差
【发布时间】:2012-08-28 16:20:48
【问题描述】:

我有这个代码;

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] 行中遇到最大递归深度错误。我希望那行得到用于当前描述符实例的变量的名称。谁能看到我在这里做错了什么?

【问题讨论】:

    标签: python exception-handling recursion descriptor


    【解决方案1】:

    getattr() 呼叫正在呼叫您的 __get__

    解决此问题的一种方法是显式调用超类object

    object.__getattribute__(instance, name)
    

    或者,更清楚:

    instance.__dict__[name]
    

    【讨论】:

    • instance.__dict__[name] 在一般情况下对于非数据描述符可能会失败。 NumberDescriptor 是一个数据描述符,所以它应该在这种情况下工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多