Duck punching in a property in python

佐手、 提交于 2019-12-03 16:22:12

Following code works :

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

But I am not sure you should be doing it.

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

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

Hope this solves your problem.

a.__dict__  #{'a': 10}
b.__dict__  #{'a': 10, 'new_a': 100}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!