我试图通过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(个体经营,价值)突变。对于一个快速测试,以验证它不会叫,我改增变到:
def setMyProperty(self, value):
raise ValueError('WTF! Why are you not being called?')
if value is None:
value = ''
self.__my_property = value
我是相当新的Python的,也许还有另一种方法做我想要做的,但有人可以解释为什么mutatator没有被调用时setattr(self,item,value)被调用?
是否有另一种通过字符串设置属性的方法?我需要在设置属性值时执行mutator中的验证。
你真的使用你的setter和getter函数定义一个属性吗?你的代码不显示这样的定义。 Python应该如何知道'my_property'使用什么getter和setter? – 2011-03-12 22:54:16
@Sven Marnach:糟糕,忘记补充说明了。但是,是的,我在实际的代码中定义了它。 – 2011-03-12 22:56:12