Need advice on subclassing code

Kent Johnson kent37 at tds.net
Tue Nov 15 11:37:49 EST 2005


Rusty Shackleford wrote:
> Hi --
> 
> We have some code that returns an object of a different class, depending
> on some parameters.  For example:
> 
> if param x is 1 and y is 1, we make an object of class C_1_1.
> if param x is 1 and y is 2, we make an object of class C_1_2.
> 
> C_1_1 and C_1_2 share a common C ancestor, and in practice may be
> identical, but theoretically, could have the same function name with two
> different implementations underneath.
> 
> We have a file where all the C_X_Y classes are defined.  
> Is this the best solution?  Is there some way of doing a default vs.
> non-default deal, without having to manually hardcode all the different
> possible subclasses?

How are you instantiating the correct class? You should be able to provide a default behaviour. For example if the classes are all defined in module C you could have a factory like this:

import C
def makeC(x, y):
  subtype = 'C_%d_%d' % (x, y)
  cls = getattr(C, subtype, C.C)
  return cls(x, y)

Then in module C just define the subtypes you need to specialize; all other values of x and y will get the base class C.C.

Kent



More information about the Python-list mailing list