Duck perforation in a property in python

I want to add the http://docs.python.org/library/functions.html#property object to the object (a specific instance of the class). Is it possible?

Some other questions about duck / monkey perforation in python:

Adding a method to an existing instance of an object

Python: changing methods and attributes at runtime

UPDATE: delnan replied in the comments

Dynamically adding @property in python

+5
source share
2 answers

The 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'm not sure you should do this.

+3
source
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}
0
source

All Articles