2

我有这个代码;

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

4

1 回答 1

11

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

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

object.__getattribute__(instance, name)

或者,更清楚:

instance.__dict__[name]
于 2012-08-28T16:27:46.140 回答