2012-08-28 151 views
1

我有這段代碼;getattr的最大遞歸深度誤差

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]獲得最大遞歸深度誤差。我希望這一行能夠獲取當前描述符實例所使用的變量的名稱。任何人都可以看到我在這裏做錯了什麼?

回答

9

getattr()致電__get__。要解決此

一種方式是通過超顯式調用,object

object.__getattribute__(instance, name) 

或者,更清晰:

instance.__dict__[name] 
+2

'實例.__字典__ [名]'可能會失敗非一般情況下的數據描述符。 'NumberDescriptor'是一個數據描述符,所以它應該在這種情況下工作。 – jfs