我试图编写一些代码来检查项目是否具有某些属性,并调用它们.我尝试用getattr做到这一点,但修改不会是永久性的.我做了一个"假"课来检查这个.这是我用于该类的代码:
class X: def __init__(self): self.value = 90 def __get(self): return self.value def __set(self,value): self.value = value value = property(__get,__set) x = X() print x.value # this would output 90 getattr(x,"value=",99) # when called from an interactive python interpreter this would output 99 print x.value # this is still 90 ( how could I make this be 99 ? )
谢谢 !
你需要做点什么
class X: def __init__(self): self._value = 90 def _get(self): return self._value def _set(self, value): self._value = value value = property(_get, _set)
请注意,"internal"变量必须具有与属性(我使用过的_value
)不同的名称.
然后,
setattr(x, 'value', 99)
应该管用.