Is this the correct way to emulate C++ function overloading?

Remco Gerlich scarblac at pino.selwerd.nl
Tue May 15 15:50:37 EDT 2001


gradha at iname.com <gradha at iname.com> wrote in comp.lang.python:

(snip)

> Questions:
> Is this the correct way of doing this?

Noooo! You don't *care* what the type is.

def print_whatever(x):
   print "The type of x is %s, value %s" % (type(x), x)
   
Making different versions of a function based on type is nonsensical in
Python.

> I have put the selection dictionary out of the print_whatever function
> to avoid it having generated every time the user calls the function.
> In C++ I would prepend a static in front of the type variable and then
> the variable would be generated/initialized only once for the process
> duration. Is there a Python equivalent of this static variable use or
> can I safely presume Python will create that dictionary only once?

It creates it when you do the assignment. If the assignment is run multiple
times, the dictionary is recreated each time.

> AFAICS the python way of avoiding this function overloading would be
> to create objects with the same function names, so looping through a
> list I can call the same member function and let it react depending
> on it's type/class, right?

I'm not sure what you mean here. It's right that if you have objects from
classes A, B and C that all define some method x(), then you can call x() on
objects from those classes, even when you don't know which it is exactly.

What that has to do with function overloading isn't clear. The Python way
there is to simply make a function that works regardless of the type of the
argument, or throw an exception if the argument really makes no sense in the
situation.

-- 
Remco Gerlich



More information about the Python-list mailing list