No method overloadin I suppose ?

Paul Magwene paul.magwene at yale.edu
Wed Apr 12 11:51:26 EDT 2000


Thomas SMETS wrote:
> 
> ## Beginning of Python program ...
> class Lister:
>   def __init__(self):
>     print 'In constructor ...'
>     __init__(1)
> 
>   def __init__(self, lValue):
>     print 'In constructor with parameter'
>     self.l = lValue
> 
>   def __repr__(self):
>     print '\n******\n\tValue is : ', l, '\n********'
> 
> if __name__ == "__main__":
>   x = Lister()
>   y = Lister (2)
> ## End of python program
> 
> Trace of execution is :
> Traceback (innermost last):
>   File "Minheritence.py", line 14, in ?
>   x = Lister()
> TypeError: not enough arguments; expected 2, got 1
> End of trace ...
> 
> I guess I can't do methods overloadin', as shown... WHY is that ? I'm
> wrong ?

You can't overload methods as you would in C++, but the following
accomplishes the same thing.  You could also test for the types of
parameters using the function type() and the types module.

--Paul


class Lister:
  def __init__(self,lValue=None):
    if lvalue:
        print "Constructed with parameter"
        self.l = lValue
    else:
        print "Default construction"
        self.l = 1

  def __repr__(self):
    print '\n******\n\tValue is : ', l, '\n********'



More information about the Python-list mailing list