1

我正在尝试通过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 内部的验证。

4

1 回答 1

4

为我工作:

>>> class MyClass(object):
...   def get(self): return 10
...   def setprop(self, val): raise ValueError("hax%s"%str(val))
...   prop = property(get, setprop)
...
>>> i = MyClass()
>>> i.prop =4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in setprop
ValueError: hax4
>>> i.prop
10
>>> setattr(i, 'prop', 12)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in setprop
ValueError: hax12

你粘贴的代码似乎和我的一样,除了我的类继承自object,但那是因为我正在运行 Python 2.6,我认为在 2.7 中所有类都自动继承自object. 不过,试试看,看看是否有帮助。

为了更清楚:试着做myClass.my_property = 4. 这会引发异常吗?如果不是,那么这是继承自的问题object- 属性仅适用于新型类,即继承自的类object

于 2011-03-12T22:59:50.353 回答