Method Overloading Simulation in Python

Simulate method overloading using default arguments and *args.

BeginnerObject-Oriented ProgramsExample 8 of 25
method-overloading-simulation.py
1# Program to simulate method overloading
2
3class Adder:
4 def add(self, *args):
5 return sum(args)
6
7a = Adder()
8print(a.add(1, 2))
9print(a.add(1, 2, 3))

Output

3
6

What's going on

Python does not support true method overloading, but *args lets one method handle varying numbers of arguments.

After this program

If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.