问题
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