In programming, function overloading occurs when we have different functions with the same name, but with different signatures (i.e., what we’re inputting in). This is one of the core concepts in object-oriented programming, where it’s used with constructors.

// in person.h
class Person {
	public:
		Person(string n);
		Person(string n, int a);
}
 
// in person.cpp
Person::Person (string n) {
	name = n;
	age = 0;
}
Person::Person (string n, int a) {
	name = n;
	age = a;
}
 
// in whatever file
Person *pp = new Person("Bill", 5);

Which constructor is called is determined by the argument types when the objects are instantiated. For instance, if we instantiate an object with a string parameter, we’ll use the first constructor in the block directly above. For example, if we define only a constructor with a string input, and we instantiate a new object without any inputs, we get an error — because we didn’t define A().

In Python

Python natively does not support function overloading.1 This limits the ability to write polymorphic code and with native Python our constructors don’t look nearly as nice as C++.

Using the multipledispatch library (from multipledispatch import dispatch),2 we have the dispatch decorator, with which we can specify input types.

@dispatch (int, int)
def add (a, b):
	return a + b # integer addition
 
@dispatch (str, int)
def add (a, b):
	return a + b # string concatenation

And just like other languages, if we input a variable with a type that isn’t supported, we run into an error.

Footnotes

  1. From this Substack article by Avi Chawla.

  2. See the Python documentation.