Advice requested on class design

Alan Ristow alan.ristow at gmail.com
Wed Apr 28 08:44:12 EDT 2010


Hi all,

I am relatively new to Python, though not to programming in general, and
using Python 2.6. I have a design problem that I cannot quite decide how to
handle and I am hoping for some advice.

I would like to have three classes, ClassA, ClassB, and ClassC, that are
essentially the same, the only difference being that each class has a
different range of valid values for its properties. Thus, the obvious
solution is to create a base class, then subclass from that and include the
required error-checking during initialization and when property values
change. The base class might look something like this:

class BaseClass(object):
    def __init__(self, arg1, arg2):
        self.a = arg1
        self.b = arg2

    @property
    def a(self):
        return self.a

    @a.setter
    def a(self, new_a):
        self.a = new_a

    @property
    def b(self):
        return b

    @b.setter
    def b(self, new_b):
        self.b = new_b

And ClassA might look something like this:

class ClassA(BaseClass):
    def __init__(self, arg1, arg2):
        assert arg1 > 0 and arg2 > 100
        BaseClass.__init__(self, arg1, arg2)

    @a.setter
    def a(self, new_a):
        assert new_a > 0
        self.a = new_a

    @b.setter
    def b(self, new_b):
        assert new_b < 100
        self.b = new_b

However, instead of rewriting my validation code in several different
places, I would prefer to write it one time and keep it in one place. I can
write a function or method that I call each time I need to do validation,
which is the approach I would take in most languages. However, since I am
basically writing several small variations on one theme, it seems like in
Python this might be an ideal application for decorators and/or metaclasses.

So my question is, what is the most sensible way to write a set of classes
such as these in Python? I am not afraid to experiment with decorators or
metaclasses -- indeed, I would love to learn more about them -- but in this
particular project I do not want to use them just for the sake of learning
to use them. If there is a good reason to use them, I am all for it, though.

All advice appreciated,

Thanks,

Alan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100428/d81626ed/attachment.html>


More information about the Python-list mailing list