Multiple initialization methods?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • alex

    #1

    Multiple initialization methods?

    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

  • Dennis Benzinger

    #2
    Re: Multiple initialization methods?

    alex wrote:[color=blue]
    > Hi,
    >
    > it is possible to define multiple initialization methods so that the
    > method is used that fits?[/color]

    No, there is no overloading in Python.
    [color=blue]
    > 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
    >[/color]

    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:

    or in the tutorial:



    Bye,
    Dennis

    Comment

    • Steven Bethard

      #3
      Re: Multiple initialization methods?

      alex wrote:[color=blue]
      > 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.[/color]

      Why don't you just write this as:

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

      STeVe

      Comment

      • Mathias Waack

        #4
        Re: Multiple initialization methods?

        alex wrote:
        [color=blue]
        > 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?[/color]

        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__.u pdate(kw)

        Mathias

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

        Comment

        • Joe Francia

          #5
          Re: Multiple initialization methods?

          On 16 Feb 2005 13:31:31 -0800, alex <alexander.diet z@mpi-hd.mpg.de> wrote:
          [color=blue]
          > 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
          >[/color]

          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('occ upation', '')

          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/

          Comment

          • xtian

            #6
            Re: Multiple initialization methods?

            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(fro mkeys)

            (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(12 34)
            u = User.getByLogin (username, password)

            Cheers,
            xtian

            Comment

            Working...