Thursday, October 18, 2007

Python Properties

Okay, Python does provide a mechanism for get- and set- methods for an instance variable: The property() function. You can find it documented in the Library Reference. Granted, I haven't really used this yet, but it exists.

There are two approaches. These examples are copied directly from the above Library Reference by Guido van Rossum, edited by Fred L. Drake, Jr.


class C(object):
def __init__(self): self.__x = None
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")


Then, there is the so-called decorator, which is quite convenient.


class Parrot(object):
def __init__(self):
self._voltage = 100000

@property
def voltage(self):
"""Get the current voltage."""
return self._voltage


I believe that this functionality doesn't work for “classic” classes. That means you have to declare your class as a subclass of object, as shown above.

There's also a mechanism for creating a property class for implementing get and set methods for a variable, but I'll have to go back and look it up.

Part of the problem is that the property() function is buried in the Reference Library but isn't part of the Tutorial under the object discussion.

Okay, there's a pretty decent discussion in the Release Notes for Python 2.2.3. It even covers the subclassing of property to make the get and set functionality work for class attributes.