Re: Overloading __init__ & Function overloading
- From: Christopher Subich <csubich.spam.block@xxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 30 Sep 2005 11:10:48 -0400
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>
.- References:
- RE: Overloading __init__ & Function overloading
- From: Iyer, Prasad C
- RE: Overloading __init__ & Function overloading
- Prev by Date: Python <=> Excel question
- Next by Date: Re: Overloading __init__ & Function overloading
- Previous by thread: Re: Overloading __init__ & Function overloading
- Next by thread: Re: Overloading __init__ & Function overloading
- Index(es):