----- "Alan Ristow" <alan.ris...@gmail.com> wrote: > 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 >
I will try not to get too religious :o) Validate your args in the base class. class Base: MIN = None MAX=None self.__init__(self, arg1, arg2): # don't use asserts, they are removed in optimized code if self.MIN is None or self.MAX is None: raise TypeError('Abstract class') if arg1 < self.MIN or arg2 > self.MAX or arg2 < arg1: raise ValueError('arg1 arg2 not in range [%s, %s]' % (self.MIN, self.MAX)) self.a = arg1 self.b = arg2 class ClassA(Base): MIN = 5 MAX = 12 class ClassB(Base): MIN = 8 MAX = 25165 JM
-- http://mail.python.org/mailman/listinfo/python-list