Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Overloading objects (http://www.velocityreviews.com/forums/t321920-overloading-objects.html)

Batista, Facundo 09-01-2003 01:55 PM

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 09-02-2003 09:58 AM

Re: Overloading objects
 
Batista, Facundo wrote:
> 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


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_stuff( somevar )
else:
self.do_other_stuff( somevar )
3. Use similar names for similar methods. wxPython does this. e.g.
def Clean( self, something ):
# common implementation

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

Hope this helps.

- Tom L


Chad Netzer 09-02-2003 11:20 AM

Re: Overloading objects
 
On Tue, 2003-09-02 at 02:58, Tom Lee wrote:
> Batista, Facundo wrote:


> > 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.


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.

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


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


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


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')

> Anyway, you have two or three choices:
>
> 1. Do it the way you're doing it.

yep.

> 2. Check parameter types at runtime using type() and the is keyword. e.g.
> if type( somevar ) is int:
> self.do_int_stuff( somevar )
> else:
> self.do_other_stuff( somevar )


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_stuff( int( some_int_like_var ) )
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.

> 3. Use similar names for similar methods. wxPython does this. e.g.


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



Tom Lee 09-02-2003 02:03 PM

Re: Overloading objects
 
Chad Netzer wrote:

> On Tue, 2003-09-02 at 02:58, Tom Lee wrote:
>
>>Batista, Facundo wrote:

>
>
>>>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.

>
>
> 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.
>
>
>>>What's the most pythonic way to do this? Using something like *args or
>>>**args?

>
>
> Yes. It is easy and powerful once you see some examples.
>
>
> [Tom Lee]
>
>>Scalability doesn't even come into this question - if you're really
>>worried about performance, don't use Python.

>
>
> 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')


Ah, cheers.

>
>
>>Anyway, you have two or three choices:
>>
>>1. Do it the way you're doing it.

>
> yep.
>
>
>>2. Check parameter types at runtime using type() and the is keyword. e.g.
>>if type( somevar ) is int:
>> self.do_int_stuff( somevar )
>>else:
>> self.do_other_stuff( somevar )

>
>
> 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_stuff( int( some_int_like_var ) )
> 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.
>


Along the same lines of the argument against isinstance right? Makes sense.

>
>>3. Use similar names for similar methods. wxPython does this. e.g.

>
>
> 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.
>


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



All times are GMT. The time now is 05:48 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.