Overloading __init__ & Function overloading

Christopher Subich csubich.spam.block at spam.subich.block.com
Fri Sep 30 17:10:48 CEST 2005

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.


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

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

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

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, 

As a concrete example of this, consider:

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

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)

More information about the Python-list mailing list