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__

これを回避する 1 つの方法は、スーパークラスを通じて明示的に呼び出すことobjectです。

object.__getattribute__(instance, name)

または、より明確に:

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