Overloading objects

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Batista, Facundo

    Overloading objects

    In others languages I can do (using sintaxis of Python):


    def myMethod (self, name):
    self.name = name

    def myMethod (self, name, age):
    self.name = name
    self.age = age


    If I'm not wrong, this is "Method Overloading".

    I thought using defaults:

    def myMethod (self, name, age=None):
    self.name = name
    if age not None:
    self.age = age


    but I'm concerned about the scalability of this.

    What's the most pythonic way to do this? Using something like *args or
    **args?

    Thank you!


    .. Facundo





    .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . .
    .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . .
    .. . . . . . . . . . . . . . .
    ADVERTENCIA

    La información contenida en este mensaje y cualquier archivo anexo al mismo,
    son para uso exclusivo del destinatario y pueden contener información
    confidencial o propietaria, cuya divulgación es sancionada por la ley.

    Si Ud. No es uno de los destinatarios consignados o la persona responsable
    de hacer llegar este mensaje a los destinatarios consignados, no está
    autorizado a divulgar, copiar, distribuir o retener información (o parte de
    ella) contenida en este mensaje. Por favor notifíquenos respondiendo al
    remitente, borre el mensaje original y borre las copias (impresas o grabadas
    en cualquier medio magnético) que pueda haber realizado del mismo.

    Todas las opiniones contenidas en este mail son propias del autor del
    mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones
    Personales S.A. o alguna empresa asociada.

    Los mensajes electrónicos pueden ser alterados, motivo por el cual
    Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación
    cualquiera sea el resultante de este mensaje.

    Muchas Gracias.

  • Tom Lee

    #2
    Re: Overloading objects

    Batista, Facundo wrote:[color=blue]
    > In others languages I can do (using sintaxis of Python):
    >
    >
    > def myMethod (self, name):
    > self.name = name
    >
    > def myMethod (self, name, age):
    > self.name = name
    > self.age = age
    >
    >
    > If I'm not wrong, this is "Method Overloading".
    >
    > I thought using defaults:
    >
    > def myMethod (self, name, age=None):
    > self.name = name
    > if age not None:
    > self.age = age
    >
    >
    > but I'm concerned about the scalability of this.
    >
    > What's the most pythonic way to do this? Using something like *args or
    > **args?
    >
    > Thank you!
    >
    >
    > . Facundo[/color]

    Scalability doesn't even come into this question - if you're really
    worried about performance, don't use Python.

    Anyway, you have two or three choices:

    1. Do it the way you're doing it.
    2. Check parameter types at runtime using type() and the is keyword. e.g.
    if type( somevar ) is int:
    self.do_int_stu ff( somevar )
    else:
    self.do_other_s tuff( somevar )
    3. Use similar names for similar methods. wxPython does this. e.g.
    def Clean( self, something ):
    # common implementation

    def CleanWithScoure r( self, something ):
    # implementation using a Scourer instead of the default cleaning
    implement

    Hope this helps.

    - Tom L

    Comment

    • Chad Netzer

      #3
      Re: Overloading objects

      On Tue, 2003-09-02 at 02:58, Tom Lee wrote:[color=blue]
      > Batista, Facundo wrote:[/color]
      [color=blue][color=green]
      > > I thought using defaults:
      > >
      > > def myMethod (self, name, age=None):
      > > self.name = name
      > > if age not None:
      > > self.age = age
      > >
      > >
      > > but I'm concerned about the scalability of this.[/color][/color]

      In general, it isn't a problem. You really don't want methods with LOTS
      of arguments. If you need variable numbers of arguments, where the
      default value system doesn't help you, just use *args, and do things
      positionally by counting the length of the argument list.

      In Python, you can always use argument keywords when you call your
      method, so you don't need to remember the positions. Learn to rely on
      keyword arguments, and your life with Python will be happier.

      Also, you can use a dictionary to hold and pass your arguments around
      easily, and can have it automatically substitute the keyword values when
      you call the function (using **kwds). If you need LOTS of arguments,
      use a dictionary or class, and pass THAT to your method.
      [color=blue][color=green]
      > > What's the most pythonic way to do this? Using something like *args or
      > > **args?[/color][/color]

      Yes. It is easy and powerful once you see some examples.


      [Tom Lee][color=blue]
      > Scalability doesn't even come into this question - if you're really
      > worried about performance, don't use Python.[/color]

      I assume the original poster was concerned with the scaling of the
      number of arguments, and it becoming unmanagable to use and maintain.
      Not anything to do with speed (ie. a different kind of 'scaling')
      [color=blue]
      > Anyway, you have two or three choices:
      >
      > 1. Do it the way you're doing it.[/color]
      yep.
      [color=blue]
      > 2. Check parameter types at runtime using type() and the is keyword. e.g.
      > if type( somevar ) is int:
      > self.do_int_stu ff( somevar )
      > else:
      > self.do_other_s tuff( somevar )[/color]

      Rather than doing explicit type checks, it is somehat more robust to try
      to operate on the argument as if it were a valid type, and be prepared
      to handle exceptions. Only coerce to another to another type when you
      need to:

      try:
      self.do_int_stu ff( int( some_int_like_v ar ) )
      except TypeError:
      [handle the other cases or error]

      If you do want to have set types (as one often does), try to test based
      on behavior, since many objects can act similarly and interact together,
      without being the same type (and so type checking will always be overly
      restrictive and reduce the utility of your design)

      Anyway, it is a tangential, and somewhat more advanced topic than this
      thread was started to cover.
      [color=blue]
      > 3. Use similar names for similar methods. wxPython does this. e.g.[/color]

      yep. Although that's not my favorite design. Just makes it harder to
      learn things by introspection (requires more reference manual searching
      than using fewer methods with more option arguments, (IMO)) It's a
      tricky balance, sometimes.

      --
      Chad Netzer


      Comment

      • Tom Lee

        #4
        Re: Overloading objects

        Chad Netzer wrote:
        [color=blue]
        > On Tue, 2003-09-02 at 02:58, Tom Lee wrote:
        >[color=green]
        >>Batista, Facundo wrote:[/color]
        >
        >[color=green][color=darkred]
        >>>I thought using defaults:
        >>>
        >>>def myMethod (self, name, age=None):
        >>> self.name = name
        >>> if age not None:
        >>> self.age = age
        >>>
        >>>
        >>>but I'm concerned about the scalability of this.[/color][/color]
        >
        >
        > In general, it isn't a problem. You really don't want methods with LOTS
        > of arguments. If you need variable numbers of arguments, where the
        > default value system doesn't help you, just use *args, and do things
        > positionally by counting the length of the argument list.
        >
        > In Python, you can always use argument keywords when you call your
        > method, so you don't need to remember the positions. Learn to rely on
        > keyword arguments, and your life with Python will be happier.
        >
        > Also, you can use a dictionary to hold and pass your arguments around
        > easily, and can have it automatically substitute the keyword values when
        > you call the function (using **kwds). If you need LOTS of arguments,
        > use a dictionary or class, and pass THAT to your method.
        >
        >[color=green][color=darkred]
        >>>What's the most pythonic way to do this? Using something like *args or
        >>>**args?[/color][/color]
        >
        >
        > Yes. It is easy and powerful once you see some examples.
        >
        >
        > [Tom Lee]
        >[color=green]
        >>Scalability doesn't even come into this question - if you're really
        >>worried about performance, don't use Python.[/color]
        >
        >
        > I assume the original poster was concerned with the scaling of the
        > number of arguments, and it becoming unmanagable to use and maintain.
        > Not anything to do with speed (ie. a different kind of 'scaling')[/color]

        Ah, cheers.
        [color=blue]
        >
        >[color=green]
        >>Anyway, you have two or three choices:
        >>
        >>1. Do it the way you're doing it.[/color]
        >
        > yep.
        >
        >[color=green]
        >>2. Check parameter types at runtime using type() and the is keyword. e.g.
        >>if type( somevar ) is int:
        >> self.do_int_stu ff( somevar )
        >>else:
        >> self.do_other_s tuff( somevar )[/color]
        >
        >
        > Rather than doing explicit type checks, it is somehat more robust to try
        > to operate on the argument as if it were a valid type, and be prepared
        > to handle exceptions. Only coerce to another to another type when you
        > need to:
        >
        > try:
        > self.do_int_stu ff( int( some_int_like_v ar ) )
        > except TypeError:
        > [handle the other cases or error]
        >
        > If you do want to have set types (as one often does), try to test based
        > on behavior, since many objects can act similarly and interact together,
        > without being the same type (and so type checking will always be overly
        > restrictive and reduce the utility of your design)
        >
        > Anyway, it is a tangential, and somewhat more advanced topic than this
        > thread was started to cover.
        >[/color]

        Along the same lines of the argument against isinstance right? Makes sense.
        [color=blue]
        >[color=green]
        >>3. Use similar names for similar methods. wxPython does this. e.g.[/color]
        >
        >
        > yep. Although that's not my favorite design. Just makes it harder to
        > learn things by introspection (requires more reference manual searching
        > than using fewer methods with more option arguments, (IMO)) It's a
        > tricky balance, sometimes.
        >[/color]

        Yeah, but by the same token it makes your methods a little easier to
        read. I agree, however.

        Comment

        Working...