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

gradha at iname.com gradha at iname.com
Tue May 15 06:44:12 EDT 2001


Hi.

Since Python functions don't declare types for the arguments (unless I
misread the documentation), I have tried to implement C++ like function
overloading with the following example, and I have a few questions
about it (see below):

	#!/usr/bin/env python
	
	def print_number (value):
		print "number %d" % (value)
	
	def print_string (value):
		print "string %s" % (value)
	
	def print_float (value):
		print "float %f" % (value)
	
	selection = {
		"<type 'string'>": print_string,
		"<type 'int'>": print_number,
		"<type 'float'>": print_float}
	
	def print_whatever (value):
		try:
			selection["%s" % type (value)](value)
		except KeyError, msg:
			print "Sorry, %s not overloaded" % type (value)
			raise KeyError, msg
	
	# Here starts the test
	if __name__ == "__main__":
		print_whatever ("my string")
		print_whatever ("my int (this is fake)")
		print_whatever (1235)
		print_whatever (1235.2134)
		print_whatever (None)

Questions:
Is this the correct way of doing this?

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?

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? But what when you don't need to create
objects or want to do it with built-in types? Is there another way?

-- 

 Grzegorz Adam Hankiewicz   gradha at iname.com   http://gradha.infierno.org



More information about the Python-list mailing list