Duck punching in a property in python

允我心安 提交于 2019-12-05 00:37:13

问题


I'd like to be able to add a property http://docs.python.org/library/functions.html#property to an object (a specific instance of a class). Is this possible?

Some other questions about duck punching/monkey patching in python:

Adding a Method to an Existing Object Instance

Python: changing methods and attributes at runtime

UPDATE: Answered by delnan in the comments

Dynamically adding @property in python


回答1:


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.




回答2:


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}


来源:https://stackoverflow.com/questions/5415679/duck-punching-in-a-property-in-python

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