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]
獲得最大遞歸深度誤差。我希望這一行能夠獲取當前描述符實例所使用的變量的名稱。任何人都可以看到我在這裏做錯了什麼?
'實例.__字典__ [名]'可能會失敗非一般情況下的數據描述符。 'NumberDescriptor'是一個數據描述符,所以它應該在這種情況下工作。 – jfs