Generic Python

Andrae Muys amuys at shortech.com.au
Mon Jun 24 21:30:26 EDT 2002


Michael Chermside <mcherm at destiny.com> wrote in message news:<mailman.1024928731.22453.python-list at python.org>...
> (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
> 

And naturally you can extend this slightly with a closure to avoid
having to declare all your methods in the class upfront ie.

class Base:
    def __init__(self, text):
        def closure():
            print text
        self._output = closure
    def output(self):
        self._output()

b = Base("Hello")
c = Base("World")
b.output()
Hello
c.output()
World

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

Agreed.  The original post requested generic python, AFAIK this is
best done by runtime definition of classes inside factory
methods/functions.

Andrae Muys



More information about the Python-list mailing list