June 29, 2022

Method Overloading in Python With Examples

In this post we’’ll see how Method Overloading in Python works.

What is Method Overloading

Method overloading is also an object oriented programming concept which states that in a single class you can have two or more methods having the same name where the methods differ in types or number of arguments passed.

Method Overloading in Python

Method overloading is not supported in Python. In Python if you try to overload a method there won't be any compile time error but only the last defined method is recognized. Calling any other overloaded method results in an error at runtime.

For example following is a class definition with two overloaded methods one with 2 arguments and another one with 3 arguments.

class OverloadExample:
  # sum method with two parameters
  def sum(self, a, b):
    s = a + b
    print('Sum is:', s)

  # overloaded sum method with three parameters
  def sum(self, a, b, c):
    s = a + b + c
    print('Sum is:', s)


obj = OverloadExample()
obj.sum(1,2,3)
obj.sum(4, 5)
Output
Sum is: 6
Traceback (most recent call last):
  File "F:/knpcode/Python/Programs/Overload.py", line 15, in 
    obj.sum(4, 5)
TypeError: sum() missing 1 required positional argument: 'c'

As you can see method with 3 arguments is the last one so that can be called but calling the sum method with two arguments results in error.

How to achieve method overloading in Python

If you want to write a method in Python that can work with different number of argument or simulate method overloading then you can use default argument or variable length arguments in Python.

1. Using default arguments

Here None keyword is assigned as the default value.

class OverloadExample:
  # sum method with default as None for parameters
  def sum(self, a=None, b=None, c=None):
    # When three params are passed
    if a is not None and b is not None and c is not None:
      s = a + b + c
      print('Sum is:', s)
    # When two params are passed
    elif a is not None and b is not None:
      s = a + b
      print('Sum is:', s)


obj = OverloadExample()
obj.sum(1, 2, 3)
obj.sum(4, 5)
Output
Sum is: 6
Sum is: 9

2. Using variable length arguments

You can use a variable length argument that can accept different number of values.

class OverloadExample:
  def sum(self, *args):
    s = 0
    for num in args:
      s += num
    print('Sum is:', s)


obj = OverloadExample()
obj.sum(1, 2, 3)
obj.sum(4, 5)
Output
Sum is: 6
Sum is: 9

That's all for the topic Method Overloading in Python With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment