Generic Python

Michael Chermside mcherm at destiny.com
Mon Jun 24 10:27:22 EDT 2002


Uwe writes:
> is it possible to to write a class which, f.e. takes an argument in
> __init__() and that doesn't return an instance object but a new class
> object?
> 
> The problem is that  [.....]
        [Detailed explanation follows]

So far I've seen suggestions that:
   (1) Create a factory function which returns the appropriate class.
   (2) Somehow use exec to build the classes at runtime.
   (3) Use metaclass programming.

I would suggest that (1) is by far the best solution, and that you stay 
away from (2) and (3) unless you KNOW what you are doing, or you are 
more interested in playing around (and learning) than getting your 
problem solved.

But just to be confusing, I'm going to add a (4)th solution, completely 
different from the other three!


(4) In python, you can change individual methods of an instance, so you 
may not even NEED to have many separate classes, if they differ only in 
that one method.

Here is an illustration of how it would work:

Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> class Base:
...     def output_0(self):
...         print 'zero'
...     def output_1(self):
...         print 'one'
...     def output_2(self):
...         print 'two'
...     def __init__(self, n):
...         self.output = (
...             [self.output_0, self.output_1, self.output_2] [n] )
...
 >>> b = Base(0)
 >>> b.output()
zero
 >>> b = Base(2)
 >>> b.output()
two


HOWEVER... if your subclasses need more than just the one function 
defined in them, then you are better off going with solution (1) above.

-- Michael Chermside






More information about the Python-list mailing list