Multiple initialization methods?

Discussion in 'Python' started by alex, Feb 16, 2005.

  1. alex

    alex Guest

    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
    alex, Feb 16, 2005
    #1
    1. Advertising

  2. alex wrote:
    > 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
    Dennis Benzinger, Feb 16, 2005
    #2
    1. Advertising

  3. alex wrote:
    > 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
    Steven Bethard, Feb 16, 2005
    #3
  4. 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?
    Mathias Waack, Feb 16, 2005
    #4
  5. alex

    Joe Francia Guest

    On 16 Feb 2005 13:31:31 -0800, alex <> 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/
    Joe Francia, Feb 16, 2005
    #5
  6. alex

    xtian Guest

    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
    xtian, Feb 17, 2005
    #6
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JKop
    Replies:
    10
    Views:
    937
  2. Matthias Kaeppler
    Replies:
    2
    Views:
    437
    Victor Bazarov
    Jul 18, 2005
  3. Replies:
    6
    Views:
    458
    Ron Natalie
    Dec 11, 2005
  4. toton
    Replies:
    5
    Views:
    931
    Victor Bazarov
    Sep 28, 2006
  5. Kenneth McDonald
    Replies:
    5
    Views:
    312
    Kenneth McDonald
    Sep 26, 2008
Loading...

Share This Page