Implementing class attribute access methods via pseudo-function o verloading.

Lonnie Princehouse finite.automaton at gmail.com
Mon Oct 25 13:57:29 EDT 2004


> Am I correct in stating that Python does not support function overloading? 

Technically, yes.  Two methods with the same name can't coexist in the
same namespace.  Overloading makes sense in C++ because the compiler
is able to decide which function to use at compile time based on
number and type of arguments.  Python is (a) not compiled and (b) not
statically typed, so overloading as a part of the language makes a lot
less sense.

You yourself have demonstrated why overloading isn't necessary:  A
function can implement its own dispatch mechanism when invoked, based
on inspection of the arguments passed to it.

Additionally, considering that one can write functions with totally
arbitrary calling sequences,

def foo(*args, **keywords):
  ...

...you can go _beyond_ the C++ notion of overloading --- a mechanism
that only takes number and type of arguments into account.

As an example, here's one common way of simulating overloading with
Python.  We'll dispatch to functions that follow a certain naming
convention based on the class name of the argument:

def foo(arg):
   try:
      subfunc = eval("foo_%s" % arg.__class__.__name__)
   except:
      subfunc = foo_default
   return subfunc(arg)

def foo_default(arg):
   print "default foo behavior"

def foo_int(arg):
   print "argument is an integer"

def foo_str(arg):
   print "argument is a string"


foo('hello world')
>>> argument is a string

foo(23)
>>> argument is an integer

foo({})  # we didn't implement foo_dict
>>> default foo behavior



More information about the Python-list mailing list