猛击在Python的物产的鸭子

Con*_*ens 5 python monkeypatching properties

我希望能够将属性http://docs.python.org/library/functions.html#property添加到对象(类的特定实例).这可能吗?

关于python中鸭子打孔/猴子修补的其他一些问题:

将方法添加到现有对象实例

Python:在运行时更改方法和属性

更新:由delnan在评论中回答

在python中动态添加@property

Rum*_*kin 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
Run Code Online (Sandbox Code Playgroud)

但我不确定你应该这样做。