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

Hannah Schroeter hannah at schlund.de
Tue May 15 21:31:19 CEST 2001


Hello!

In article <s91rd9.q7r.ln at 127.0.0.1>,  <gradha at iname.com> wrote:

>Since Python functions don't declare types for the arguments (unless I
>misread the documentation),

Right. Python does IIRC not have type declarations, not even optional ones.

>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)

This should work. However, it is a bit inefficient (you compare
type identifiers as *strings* instead of type objects or things like
that), and it doesn't exactly simulate C++'s overloading. The latter
is resolved at compile time, using the statically declared types,
while you resolve the "overloading" at run-time, using the dynamic
object types.

That would be akin to (sorry for foreign language):

(defgeneric print-whatever (object))

(defmethod print-whatever ((object float))
  (print-float object))
(defmethod print-whatever ((object string))
  (print-string object))
(defmethod print-whatever ((object number))
  (print-number object))

; float encompasses *all* float types, regardless of precision
; number is a superclass of float, encompassing complex and integer
; numbers in addition to floats.

In Python, that would be (if strings, integers and floats were classes
and you could add methods to them), modifying the source:

class string ...:
    ... old methods ...
    def print_whatever(self):
        print_string(self)

class float ...:
    ... old methods ...
    def print_whatever(self):
        print_float(self)

...

>[...]

>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?

In principle yes.

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

Probably not, however I don't know the python details too much (yet).
Is there something like
  (subtypep (type-of object) 'string)
or
  (typecase ...)?

Kind regards,

Hannah.



More information about the Python-list mailing list