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.
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.
And just like other languages, if we input a variable with a type that isn’t supported, we run into an error.
Footnotes
-
From this Substack article by Avi Chawla. ↩
-
See the Python documentation. ↩