Method Overloading in Python

Python does not support method overloading. In case, you overload methods then you will be able to access the last defined method.

class Mathematics:
   def add(self, a, b):
      print(a + b)
   def add(self, a, b, c):
      print(a + b + c)

obj = Mathematics()
obj.add(8, 9, 12)

Output of the above program

29

As you can see that we have defined two add() methods having a different number of arguments but you can only call the last defined method. If you call the other method then you will get an error. Suppose, you write obj.add(8, 9) and run the program then you will get an error stating that you are missing one argument.

How to implement method overloading in Python?

Use arbitrary arguments in a function to achieve method overloading.

class Mathematics:
   def add(self, *args):
      sum = 0
      for a in args:
         sum = sum + a
      print(sum)

obj = Mathematics()
obj.add(8, 9, 12)
obj.add(8, 9)

Output of the above program

29
17