Multiple initialization methods?
Joe Francia
gmane-schpam at joefrancia.com
Wed Feb 16 17:04:30 EST 2005
On 16 Feb 2005 13:31:31 -0800, alex <alexander.dietz at mpi-hd.mpg.de> wrote:
> 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.
--
Soraia: http://www.soraia.com/
More information about the Python-list
mailing list