Python Practice › OOP Programs › Program 13

Method overloading

MediumOOP Programs · 13 of 48

Write a Python program that shows how to achieve method overloading.

Advertisement
Output
5
9
0

Approach

  1. Python keeps only the last method with a given name, so use default and variable arguments instead.

Solution

Python
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.

More oop programs

← All 48 OOP Programs

Leave a Comment