Re: Overloading __init__ & Function overloading
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Overloading __init__ & Function overloading

From: Christopher Subich <csubich.spam.block@spam.subich.block.com>
Date: Fri Sep 30 2005 - 17:10:48 CEST

Iyer, Prasad C wrote:
> Thanks a lot for the reply.
> But I want to do something like this
>
> class BaseClass:
> def __init__(self):
> # Some code over here
> def __init__(self, a, b):
> # Some code over here
> def __init__(self, a, b, c):
> # some code here
>
> baseclass1=BaseClass()
> baseclass2=BaseClass(2,3)
> baseclass3=BaseClass(4,5,3)

In my experience, the vast majority of cases where you "want" function
overloading, you really just want sensible default parameters. Since
Python is dynamically typed, the other common use case in static-typed
language (to provide f(int,int), f(float,float), f(double,complex),
f(Momma,Poppa) equivalents) is entirely unnecessary.

Try:

class BaseClass:
    def __init__(self, a = None, b = None, c = None):
       if a == None:
          <etc>

or (if you want to take any number of parameters)

class BaseClass:
    def __init__(self, *args):
       if len(args) == 0:
          <etc>

Of course, this is assuming that the behaviour is radically different
based on the number of arguments, which is generally Poor Design. You
probably _REALLY_ want:

class BaseClass:
    def __init__(self, a=SensibleDefault1, b=SensibleDefault2,
c=SensibleDefault3):
       <etc>

As a concrete example of this, consider:

class Point:
    def __init__(self, x=0, y=0, z=0):
       <etc>

Then you can call it with:
originPoint = Point()
pointInX = Point(xloc)
pointInXYPlane = Point(xloc,yloc)
pointIn3DSpace = Point(xloc,yloc,zloc)
<note, normally I loathe CaMeLcAsE, but it's readable in this context>

Or if the Defaults aren't quite so simple, and sensible defaults depend
on previous values, use:

class BaseClass:
    def __init__(self, a=SensibleDefault1, b=None, c=None):
       if b==None:
          b = stuff_involving(a)
       if c==None:
          c = stuff_involving(a,b)
       <etc>
Received on Sat Oct 15 04:00:23 2005