2011-03-24 34 views
5

我希望能夠將一個屬性http://docs.python.org/library/functions.html#property添加到對象(一個類的特定實例)。這可能嗎?在python中打孔的鴨子

在蟒蛇大約鴨衝/猴子打補丁的一些其他問題:

Adding a Method to an Existing Object Instance

Python: changing methods and attributes at runtime

更新:通過delnan在評論

Dynamically adding @property in python

+2

@Conley:你有相當長的一段鏈接出現,爲什麼會沒有人解決問題了嗎?你能解釋一下你的情況有什麼不同嗎? – 2011-03-24 07:40:30

+0

@Conley:同意@ Space_C0wb0y,第二個鏈接似乎有你需要的答案 – juanchopanza 2011-03-24 07:47:24

+2

公平地說,添加一個屬性需要的不僅僅是添加一個方法或屬性 - 後者的方法不起作用,在後者的情況下是一個輔助函數。然而,這已被問及[在python中動態添加@property](http://stackoverflow.com/questions/2954331/dynamically-adding-property-in-python)。 – delnan 2011-03-24 15:22:45

回答

3

下面的代碼工作已回答:

#!/usr/bin/python 

class C(object): 
    def __init__(self): 
     self._x = None 

    def getx(self): 
     print "getting" 
     return self._x 
    def setx(self, value): 
     print "setting" 
     self._x = value 
    def delx(self): 
     del self._x 
    x = property(getx, setx, delx, "I'm the 'x' property.") 

s = C() 

s.x = "test" 
C.y = property(C.getx, C.setx, C.delx, "Y property") 
print s.y 

但我不確定你應該這樣做。

+0

-1:這會將屬性添加到類中,而不僅僅是一個對象。 – 2011-03-24 07:39:18

+0

@ Space_C0wb0y:收取有罪。 – 2011-03-24 08:33:19

0
class A: 
    def __init__(self): 
     self.a=10 

a=A() 
print a.__dict__ 
b=A() 
setattr(b,"new_a",100) 
print b.__dict__ 

希望這可以解決您的問題。

a.__dict__ #{'a': 10} 
b.__dict__ #{'a': 10, 'new_a': 100}