Overloading objects

Bob Gailer bgailer at alum.rpi.edu
Mon Sep 1 14:12:24 EDT 2003


At 10:55 AM 9/1/2003 -0300, 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?

Depends. In your example, overloading is resolved by the # of args passed, 
and their meaning depends on their position. If that is all you want, 
specify defaults as in age=None. Overloading can also depend on the type of 
data passed to the method, in which case you'll need either an if .. elif 
structure or a dictionary keyed by types to resolve things.

You can also define different methods with the same name by subclassing and 
using instances of the various subclasses in your various situations. This 
approach obviates the need for overloading and can make the intent of the 
program a lot clearer to the reader.

IMHO the latter is a better way to deal with complex situations. I often 
find myself coding default values and if elif structures, and a bell rings 
reminding me to sublcass. The result is almost always better.

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20030901/b28e9b4d/attachment.html>
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003


More information about the Python-list mailing list