Python中属性的鸭子打洞
我想给一个对象(一个类的具体实例)添加一个属性,http://docs.python.org/library/functions.html#property。这样做可以吗?
还有一些关于在Python中进行“鸭子打补丁”或“猴子补丁”的问题:
更新:在评论中,delnan给出了答案
2 个回答
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}
希望这能解决你的问题。
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
不过我不太确定你这样做是否合适。