[Tutor] General programming questions

Alan Gauld alan.gauld at freenet.co.uk
Thu Oct 27 12:36:35 CEST 2005


> 1: I need to create objects that have variable levels of behaviour
> (controlled perhaps by a .config file). I can do the file reading, etc.
> - but how do I implement the behaviour, apart from just re-writing all
> the functions for each config level?

Usually by having multiple subclasses and instantiating the right kind
of object based on the config file valuyes - perhaps using a factory
object to do the config reading and instantiating.

ie You have a singleton factory object that takes a config file as its
constructor. It then interprets the config file and instantiates the
appropriate subclasses of your entity.

This is probably the easiest form of meta class programming.

> 2: I need to implement polmorphism in some methods (and a constructor).
> At the moment, I have something like:
>
> def __init__ (self, a, b, c):
> if type(a) == type("a")
>     then.....
> elif type(a) == type(["a"])
>     then....

Thats pretty much the code I'm suggesting would be in the factory
class method that processes the config file. The then... part translates
to a constructor call for each type of subclass.

> I'm sure there must be a better way to do this (both the polymorphism
> and the type testing) - but I don't know how to do it.

Multiple constructors is not easily done in Python because the parameters
to init are untyped. (You can fake it a little with default argument values)
Thats why I tend to go for a factory object which does the dynamic
decision making and leaves the init methods of the individual subclasses
clean - ie easier to reuse.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld






More information about the Tutor mailing list