473,396 Members | 1,864 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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.

Jul 18 '05 #1
3 1669
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

Jul 18 '05 #2
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
Jul 18 '05 #3
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.

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Terje Slettebø | last post by:
To round off my trilogy of "why"'s about PHP... :) If this subject have been discussed before, I'd appreciate a pointer to it. I again haven't found it in a search of the PHP groups. The PHP...
4
by: Dave Theese | last post by:
Hello all, I'm trying to get a grasp of the difference between specializing a function template and overloading it. The example below has a primary template, a specialization and an overload. ...
5
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that...
7
by: Eckhard Lehmann | last post by:
Hi, I try to recall some C++ currently. Therefore I read the "Standard C++ Bible" by C. Walnum, A. Stevens and - of course there are chapters about operator overloading. Now I have a class...
7
by: pauldepstein | last post by:
A book I have describes a class called vector. It then explains (and I understand) the concept of a copy constructor, which is needed to interpret statements like vector b = a; But then I...
3
by: toton | last post by:
Operator overloading has a sort syntax rather than member function call for stack based memory allocation. like complex<int> c1,c2,c3; c3= c1+c2; How the same can be applied to heap based...
3
by: Chameleon | last post by:
What is better if you want upcasting in intermediate classes like below? Multiple Inheritance and Overloading or simply RTTI? RTTI wants time but MI and Overloading create big objects (because of...
3
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj,...
9
by: sturlamolden | last post by:
Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by...
8
by: Wayne Shu | last post by:
Hi everyone, I am reading B.S. 's TC++PL (special edition). When I read chapter 11 Operator Overloading, I have two questions. 1. In subsection 11.2.2 paragraph 1, B.S. wrote "In particular,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.