Generic Python

Gonçalo Rodrigues op73418 at mail.telepac.pt
Mon Jun 24 08:51:36 EDT 2002


On Mon, 24 Jun 2002 11:20:37 +0200, Uwe Mayer
<Uwe.Mayer at ifib.uni-karlsruhe.de> wrote:

>Hi,
>
>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 I've got a base class and there should be many
>subclasses of it. Each subclass just overwriting an output method and
>serving as a template: 
>
>class base1:
>    def __init__(self):
>        ...
>    def output(self):
>        ...
>
>class template1(base1):
>    def output(self):
>        ...
>
>class template2(base1):
>    def ouptut(self):
>        ...
>
>I need many, many of these "template" classes, so a sorter way would be
>to accustom the base class to take another argument which then outputs
>the right thing:
>
>
>class base2:
>    def __init__(self, text):
>       ...
>    def output(self):
>       print self.text
>
>template1 = base2('some text')
>template2 = base2('another example')
>...
>
>My problem with this is that this produces instance objects and in the
>above example I had class objects. I can hardly use the latter case
>because I would always modify the original.
>I also cannot create new templates as I need them, because I'm writing
>utility classes which are much more complex and take much more
>arguments.
>
>Is it somehow possible to have the "base2" class return a class instead
>of an instance?
>Is there another way to solve this problem?
>
>Thanks in advance
>Uwe

This leads into metaclass programming. Read GvR's descintro on Python
2.2, it has some material - it may be all you need. Roughly you need
something like

class Whatever(type):
    ...

type is the mother of all metaclasses, its instances are classes
themselves.

Hope it helped, all the best,
Gonçalo Rodrigues 




More information about the Python-list mailing list