python中的Duck-punching属性

2024-04-26 07:32:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够将属性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


Tags: to对象实例orghttpdocs属性html
2条回答

以下代码工作:

#!/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}$

相关问题 更多 >