[Tutor] Contructor Overloading and Function Tooktips

Alan Gauld alan.gauld at freenet.co.uk
Tue Apr 19 21:34:19 CEST 2005


> OK, but that was just your example :-)  Here is some ugly quick code
> which might show you how to meet you needs:
>
> class JohnsMultiInitClass:
>      def __init__(self, first, second):
>          if type(first) == type(second) == str:
>              self.string_init(first, second)
>          if type(first) == type(second) == int:
>              self.int_init(first, second)

> getting an handle on OOP, and dangerous only in Python. But, I
suspect
> that this is not the Python way to do this sort of thing. (Perhaps
> people with C++ experience can weigh in to confirm or deny.)

This is an acceptable way of doing it when needed, but one thing
to note about Python is that it is rarely needed - at least, much
less commonly than in C++/Java. The reason for this is that C++
is statically typed so you are limited in what you can do to the
parameters of a method based on it's type, in Python you can often
use the same method for a wide variety of types because the binding
is done at runtime. So long as the input argument responds to the
messages sent to it, it can be used.

Another way that multiple constructors etc can be simlified (and
this is true in C++ too, but for some reason not used as much) is
via default arguments. So you can do:

def foo(anInt = 1, aFloat = 2.0, aString= '3'): pass

foo()          #--> foo(1,2.0,'3')
foo(42)        #--> foo(42,2.0,'3')
foo(14,5.7)    #--> foo(14,5.7,'3')
foo(7,8.0,'b') #--> foo(7,8.0,'b')

So from the caller's perspective there are 4 possible signatures
but only one function definiton. As I said, you can do this in
C++ too but it's less commonly seen, at least in my experience.

Finally the Python mechanisms for multiple arguments can be used
and in particular the keywords technique can provide for multiple
input values/types.

So between all the various options you can do any of the
things C++/Java does and often with much less code!

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list