Look at this small snippet of Python code:
x = TooMuchAlcohol()
x.value = 10
print x.value
x.value = 'foo'
print x.value
x.value = [1,2,3]
print x.value
Seems like nothing special, but look what it spits out:
20
foofoo
[1, 2, 3, 1, 2, 3]
Oh my god, I see everything double!
While it looks like we just write and read the attribute value
of the object x
, there is actually some additional processing taking place behind the scenes.
The trick is the Python built-in property
. With this function (or is it a class?) you can hide getter and setter functions behind what looks like standard attribute access.
As an illustration, the implementation of the TooMuchAlcohol
class used above is as follows:
class TooMuchAlcohol(object):
def _get_value(self):
return self._value * 2
def _set_value(self, value):
self._value = value
value = property(_get_value, _set_value)
The setter function _set_value()
just stores the value in a "private" attribute _value
. The getter function _get_value()
returns this value multiplied by two. And finally, the magic is in the last line, where the getter and setter are tied to the public (class) attribute value
.
For more info:
- The Python documentation on "property"
- This blog post by Adam Gomaa gives a nice, more in-depth discussion