[Tutor] About property() - For Marco Rompré

Ricardo Aráoz ricaraoz at gmail.com
Sat Apr 24 07:19:10 CEST 2010

Hi Marco (and everybody),
    in another thread you showed your code and made extensive use of
property(). Wrongful use I might say.
Let's see an example:
>>> class C(object):
...     def __init__(self): self._x = None
...     def getx(self): return self._x - 10
...     def setx(self, value): self._x = -value
...     def delx(self): del self._x
...     x = property(getx, setx, delx, "I'm the 'x' property.")
>>> c = C()
>>> c.x = 23
>>> c.x

as you can see you don't call setx() or getx() directly, you just
operate straight with x and setx() or getx() get automatically called
(c.x is given -value, that is -23 on setx(), and then we subtract 10 to
-23 giving -33).
What's more, you don't use property() nor setters and getters to do """
self._x = value """ that makes no sense, in that case you would use just
x and get done with it. You usually use c.x = 22 and if you have the
need of a setter or getter to process x before setting or getting *then*
you start using the setters and getters.

More information about the Tutor mailing list