property() usage - is this as good as it gets?
David Moss
drkjam at gmail.com
Fri Aug 22 12:18:31 EDT 2008
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?
#!/usr/bin/env python
class A(object):
def __init__(self):
self._x = None
self._y = None
def _set_x(self, value):
self._x = value
def _get_x(self):
return self._x
x = property(_get_x, _set_x)
def _set_y(self, value):
self._y = value
def _get_y(self):
return self._y
y = property(_get_y, _set_y)
class B(A):
def __init__(self):
self._z = None
super(B, self).__init__()
def _set_x(self, x):
# An example subclass 'set' override.
if x == 10:
raise Exception('%r is invalid!' % x)
self._x = x
x = property(A._get_x, _set_x)
def _set_z(self, value):
self._z = value
def _get_z(self):
return self._z
z = property(_get_z, _set_z)
del A._get_x, A._set_x, A._get_y, A._set_y
del B._set_x, B._get_z, B._set_z
More information about the Python-list
mailing list