5

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

Community
  • 1
  • 1
Conley Owens
  • 8,691
  • 5
  • 30
  • 43
  • 2
    @Conley: You have quite some links there, why could none of them solve your problem? Can you explain what is different in your scenario? – Björn Pollex Mar 24 '11 at 07:40
  • @Conley: Agreeing with @Space_C0wb0y, the second link seems to have the answers you need – juanchopanza Mar 24 '11 at 07:47
  • 2
    To be fair, adding a property requires more than adding a method or attribute - the approach for the latter doesn't work, and there can't be a helper function as in the case of the latter. However, this was already asked and solved in [Dynamically adding @property in python](http://stackoverflow.com/questions/2954331/dynamically-adding-property-in-python). –  Mar 24 '11 at 15:22
  • @Space_C0wb0y,@jaunchopanzo: The only difference is that I would prefer to have a property over a run-of-the mill method. @delnan: Thanks, exactly what I was looking for. – Conley Owens Mar 24 '11 at 16:06
  • @delnan make that an answer so @conley can accept it? – chmullig Mar 24 '11 at 16:49
  • Boy, did I misread that Q title in the middle of the night... – Apache Dec 05 '13 at 23:56

2 Answers2

3

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.

Rumple Stiltskin
  • 9,597
  • 1
  • 20
  • 25
0
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}
deeshank
  • 4,286
  • 4
  • 26
  • 32