【问题标题】:Setting Property via a String通过字符串设置属性
【发布时间】:2011-03-12 22:51:28
【问题描述】:

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

【问题讨论】:

  • 你真的用你的setter和getter函数定义了一个属性吗?您的代码没有显示这样的定义。 Python 应该如何知道 my_property 使用什么 getter 和 setter?
  • @Sven Marnach:糟糕,忘记在示例中添加该内容。但是,是的,我是在实际代码中定义的。

标签: python properties setattr


【解决方案1】:

为我工作:

>>> 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 继承的类。

【讨论】:

  • 其实最后一段就是解决办法:Python 2.7 还是区分旧式和新式的类。
  • 问题不是指定它继承自 object。谢谢。
猜你喜欢
  • 2012-03-21
  • 1970-01-01
  • 2013-03-11
  • 2010-11-08
  • 2019-03-12
  • 1970-01-01
  • 2019-03-12
  • 2012-05-04
  • 2011-04-12
相关资源
最近更新 更多