2024-04-26 07:32:35 发布
网友
我希望能够将属性http://docs.python.org/library/functions.html#property添加到对象(类的特定实例)。这可能吗?在
关于在python中打鸭子/打猴子补丁的其他问题:
Adding a Method to an Existing Object Instance
Python: changing methods and attributes at runtime
更新:德尔南在评论中回答
Dynamically adding @property in python
以下代码工作:
#!/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
但我不确定你应该这么做。在
class A: def __init__(self): self.a=10 a=A() print a.__dict__ b=A() setattr(b,"new_a",100) print b.__dict__
希望这能解决你的问题。在
以下代码工作:
但我不确定你应该这么做。在
希望这能解决你的问题。在
^{pr2}$相关问题 更多 >
编程相关推荐