Need advice on subclassing code

Michael Spencer mahs at telcopartners.com
Tue Nov 15 12:34:43 EST 2005


Kent Johnson wrote:
> Rusty Shackleford wrote:
>> ...
>> 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.
>>
>> ...
> 
> 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

Or, if you actually want different classes for each set of parameters (say for 
debugging or introspection), you could compose the default ones on the fly:


import C
def makeC(x, y):
   subtype = 'C_%d_%d' % (x, y)
   cls = getattr(C, subtype, None)
   if not cls:
     # No specialized class found, so compose a default
     # This requires C.C to be a new-style class
     cls = type(subtype, (C.C,), {"__autogenerated__": True})
   return cls(x, y)

Michael






More information about the Python-list mailing list