selecting base class from user input

John Machin sjmachin at lexicon.net
Mon Aug 14 04:45:01 EDT 2006


Jackson wrote:

> I have 4 classes:
>
> Lion(Animal):
> Ant(Animal):
> Bee(Animal):
> Human(Animal):
>
> which are all subclasses of some superclass called Animal.  Now I want
> to define an occupation. For example, Worker.  A worker can exist as any
> of the 4 classes above.  Their constructors are different and I might
> want to add certain features.
>
> My first thought was to create a class called "Worker" and have the base
> class determined by a variable which is passed into the constructor.
> Most of the method calls will come from the Animal superclass anyway,
> but some method calls might come from the Lion class, for example.
>

Here are a couple of thoughts that *might* help:

(1) mix-in i.e. a class can have multiple base classes:

class AntWorker(Animal, Worker):

(2) you can create classes on the fly using the 3-argument form of the
built-in type() function:

new_cls = type(name_of_class, base_classes_tuple, dict_of_methods_etc)

so you can have just one base class (i.e. object) and populate the dict
with methods and/or you can have pre-packaged base-classes each already
containing relevant methods ... so when the order for a new tailored
class comes in you just rush about your virtual warehouse throwing
packaged base-classes into a tuple and extra methods into a dict,
attach a name tag and then type() gift-wraps it for you.

You need to read up on "method resolution order" aka "mro" before
planning what methods go in what mixin classes and what methods are
optional add-ons and what order you specify the classes in the tuple.

HTH,
John




More information about the Python-list mailing list