2011-03-12 91 views
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(個體經營,價值)突變。對於一個快速測試,以驗證它不會叫,我改增變到:

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中的驗證。

+1

你真的使用你的setter和getter函數定義一個屬性嗎?你的代碼不顯示這樣的定義。 Python應該如何知道'my_property'使用什麼getter和setter? – 2011-03-12 22:54:16

+0

@Sven Marnach:糟糕,忘記補充說明了。但是,是的,我在實際的代碼中定義了它。 – 2011-03-12 22:56:12

回答

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繼承的類。

+2

實際上,最後一段是解決方案:Python 2.7仍然區分舊式和新式類。 – 2011-03-12 23:03:12

+1

該問題未指定它從**對象**繼承。謝謝。 – 2011-03-12 23:15:05