Multiple initialization methods?

Mathias Waack M.Waack at gmx.de
Wed Feb 16 16:58:24 EST 2005


alex wrote:

> it is possible to define multiple initialization methods so that
> the method is used that fits?
> 
> I am thinking of something like this:
> 
>   def __init__(self, par1, par2):
>     self.init(par1, par2);
> 
>   def __init__(self, par1):
>     self.init(par1, None)
> 
>   def init(self, par1, par2):
>      ...
>      ...
> 
> So if the call is with one parameter only the second class is
> executed (calling the 'init' method with the second parameter set
> to 'None' or whatever. But this example does not work.
> 
> How to get it work?

You have to do the method dispatching by yourself. For variable
length parameter list you could choose this solution: 

def __init__(self, *args):
        if len(args) == 1: self.__setup1(*args)
        elif len(args) == 2: self.__setup2(*args)
        ...
def   __setup1(self, arg1):
        print "setup1"

def __setup2(self, arg1, arg2):
        print "setup2"


Or for different parameter lists which may have the same length my
suggestion would be: 

def __init__(self, **kw):
        self.__dict__.update(kw)

Mathias

PS: anyone working on a patch for multimethod dispatching for python?



More information about the Python-list mailing list