Multiple initialization methods?

A

alex

Hi,

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?

Alex
 
D

Dennis Benzinger

alex said:
Hi,

it is possible to define multiple initialization methods so that the
method is used that fits?

No, there is no overloading in Python.
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?

Alex

Use a default argument for par2 and check for that in your function:

def __init__(self, par1, par2=None):
# do something with par1

if par2 is None:
print "par2 was not given!"
else:
print "par2 is", par2


Read more in the FAQ:
http://www.python.org/doc/faq/programming.html#how-can-i-overload-constructors-or-methods-in-python
or in the tutorial:
http://docs.python.org/tut/node6.html#SECTION006710000000000000000


Bye,
Dennis
 
S

Steven Bethard

alex said:
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.

Why don't you just write this as:

def __init__(self, par1, par2=None):
self.init(par1, par2)

STeVe
 
M

Mathias Waack

alex said:
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?
 
J

Joe Francia

Hi,

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?

Alex

You can do this:

def __init__(self, *args, **kwargs):
#args is a tuple of positional args
#kwargs is a dict of named args
print args, kwargs
#real code here instead of lame print statements
try:
self.name = args[0]
except IndexError:
self.name = ''
self.occupation = kwargs.get('occupation', '')

or even better, do this:

def __init__(self, name='', occuaption='', age=0):
#named args with default values
self.name = name
self.occupation = occupation
self.age = age

Based on this, you should have enough information to make your class work.
 
X

xtian

Several people have told you about dispatching to the different methods
based on the different parameters. Another technique is to have the
different initialisation methods be static or class methods. For
example, the python dictionary type can be instantiated in a variety of
ways:

dict(a=1, b=2, c=3) -> {'a': 1, 'c': 3, 'b': 2}

dict([('a',1), ('b',2), ('c',3)]) -> {'a': 1, 'c': 3, 'b': 2}

These are examples of dispatching to different initialisers based on
the passed parameters, but there's also the fromkeys() class method,
which accepts a list of keys and will return a new dictionary with the
elements of the list as keys:

dict.fromkeys(['a','b','c']) -> {'a': None, 'c': None, 'b': None}

This could be implemented as follows:

class dict(object):
.. def __init__(self, *args, **kws):
.. # standard initialisation...
..
.. def fromkeys(cls, keys):
.. # transform the list of keys into a list of (key, value) pairs,
.. # then delegate to the standard initialiser
.. return cls([(k, None) for k in keys])
.. # or:
.. result = cls()
.. for k in keys:
.. result[k] = None
.. return result
.. fromkeys = classmethod(fromkeys)

(In 2.4, this could use decorators and generator comprehensions
instead.)

I often use this (even in languages like Java which support
overloading) when instantiating domain objects that might be retrieved
in many different ways, for example getting an instance of a user by
database id or by login details:

u = User.getById(1234)
u = User.getByLogin(username, password)

Cheers,
xtian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top