[Tutor] function overloading

Corran Webster cwebster@nevada.edu
Mon, 3 Apr 2000 15:41:04 -0700

At 5:52 PM -0400 3/4/00, D-Man wrote:
> I would like to know if Python has a few features that I like to use in
> C++, function and operator overloading.  Does python even allow
> operators to be defined for classes?

Yes, there is pretty extensive support for overloading of operators via the
double-underscored special methods, such as __add__ and __init__.  See
Section 3.3 of the Python Reference Manual for descriptions of the special
methods which are recognised by Python.

A trivial example:

class Foo:
  def __init__(self, value):
    self.value = value
  def __add__(self, other):
    return Foo(self.value + other.value)

a = Foo(5)
b = Foo(3)
c = a+b # c gets assigned Foo(8)
print c.value # prints 8

The behaviour of overloaded functions/methods (if I remember my C++
terminology correctly) are best implemented in Python using default
arguments, or by explicitly looking at the types of the arguments passed
into the function.

> I want to be able to specify both a default constructor for a class and
> a constructor that takes initial values of state as arguments.

This is best done via default arguments to the __init__ method:

class Foo:
   def __init__(self, bar = 0):
     self.bar = bar

   def printbar(self):
     print self.bar

x = Foo()
x.printbar() # prints 0

y = Foo("Spam")
y.printbar() # prints "Spam"

If you want a mutable argument as a default (such as a list or dictionary),
do not use this:

class Foo:
  def __init__(self, bar = []):

use something like this instead:

class Foo:
  def __init__(self, bar = None):
    if bar == None:
      bar = []

Once you get a better feel for how Python does things, this will make sense.