Dynamically creating propertys
Nicodemus
nicodemus at globalite.com.br
Sat Dec 28 15:00:27 EST 2002
Timothy Grant wrote:
>Is it possible to dynamically create a property? I've got some code that uses
>dynamically created attributes, but on looking at the new property stuff it
>looks like that code could be significantly improved if I could use property
>access instead.
>
You can add methods and attributes to a class after it was defined.
Suppose you have a class C, which has an attribute x, with getter and
setter methods:
>>> class C(object):
... def __init__(self):
... self._x = 0
... def getx(self):
... return self._x
... def setx(self, x):
... self._x = x
...
>>> c = C()
>>> c.getx()
0
>>> c.setx(10)
>>> c.getx()
10
Now you want the attribute '_x' to be accessed as a property, 'x'. The
only thing you have to do is to create the property wrapper and add it
to the class:
>>> C.x = property(C.getx, C.setx)
And that's it.
>>> c.x
10
>>> c.x = 0
>>> c.x
0
Note that you can also add methods to the class after it was defined.
So, you can add the acessor methods if you only have the attribute:
>>> class C(object):
... def __init__(self):
... self._x = 0
...
>>>
>>> def getx(self):
... return self._x
...
>>> def setx(self, x):
... self._x = x
...
>>> C.getx = getx
>>> C.setx = setx
>>> c = C()
>>> c.getx()
0
>>> C.x = property(C.getx, C.setx)
>>> c.x
0
>>> c.x = 10
>>> c.x
10
Hope this helps,
Nicodemus.
More information about the Python-list
mailing list