我正在尝试通过setattr(self, item, value)函数在类之外设置 Python 类属性。
class MyClass:
def getMyProperty(self):
return self.__my_property
def setMyProperty(self, value):
if value is None:
value = ''
self.__my_property = value
my_property = property( getMyProperty, setMyProperty )
在另一个脚本中,我创建了一个实例并希望指定属性并让属性修改器处理简单的验证。
myClass = MyClass()
new_value = None
# notice the property in quotes
setattr(myClass, 'my_property', new_value)
问题是它似乎没有调用setMyProperty(self, value) mutator。为了快速测试以验证它没有被调用,我将 mutator 更改为:
def setMyProperty(self, value):
raise ValueError('WTF! Why are you not being called?')
if value is None:
value = ''
self.__my_property = value
我对 Python 还很陌生,也许还有另一种方法可以做我想做的事情,但是有人可以解释为什么调用setattr(self, item, value)时没有调用 mutator吗?
还有另一种通过字符串设置属性的方法吗?在设置属性值时,我需要执行 mutator 内部的验证。