Python Practice › OOP Programs › Program 13
Method overloading
Write a Python program that shows how to achieve method overloading.
Output
5 9 0
Approach
- Python keeps only the last method with a given name, so use default and variable arguments instead.
Solution
class Calculator: def add(self, *numbers): return sum(numbers) c = Calculator()print(c.add(2, 3))print(c.add(2, 3, 4))print(c.add())Output
5 9 0
Line by line
Line 2
*numbers accepts any number of arguments, so one method covers every case.
Tip
functools.singledispatchmethod can choose a method by the type of the first argument when the behaviour must differ by type.
Learn the concept
New to this topic? Read the lesson, then come back.