property() usage - is this as good as it gets?
Christian Heimes
lists at cheimes.de
Fri Aug 22 14:24:35 EDT 2008
David Moss wrote:
> Hi,
>
> I want to manage and control access to several important attributes in
> a class and override the behaviour of some of them in various
> subclasses.
>
> Below is a stripped version of how I've implemented this in my current
> bit of work.
>
> It works well enough, but I can't help feeling there a cleaner more
> readable way of doing this (with less duplication, etc).
>
> Is this as good as it gets or can this be refined and improved
> especially if I was to add in a couple more attributes some fairly
> complex over-ride logic?
The extended property type in Python 2.6 makes it much easier to
overwrite the getter, sett or deleter of a property:
http://docs.python.org/dev/library/functions.html?highlight=property#property
class C(object):
def __init__(self): self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
class D(C):
@C.x.getter
def x(self):
return 2 * self._x
@x.setter
def x(self, value):
self._x = value // 2
Christian
More information about the Python-list
mailing list