How can we overload a Python function?



In Python, you can define a method in such a way that there are multiple ways to call it. Depending on the function definition, it can be called with zero, one, two or more parameters. This is known as method overloading.

In the given code, there is a class with one method, sayHello(). We rewrite as shown below. The first parameter of this method is set to None, which gives us the option to call it with or without a parameter.

An object is created based on the class, and we call its method using zero and one parameter. To implement method overloading, we call the method sayHello() in two ways: 1. obj.sayHello() and 2. obj.sayHello(Rambo')

We created a method that can be called with fewer arguments than it is defined to allow. We are not limited to two variables, given method can have more variables which are optional.

Example

class Human:
   def sayHello(self, name=None): 
      if name is not None:
         print ('Hello ' + name)
      else:
         print ('Hello ') 
obj = Human() 
print(obj.sayHello())
print(obj.sayHello('Rambo'))

Output

Hello 
None
Hello Rambo
None

In Python, function overloading is not supported natively, as it is in other programming languages such as Java or C++. However, we can achieve the same effect by using default arguments and/or variable-length arguments.

Example

Here's an example using default arguments

In this example, the function "add" can take two or three arguments. If only one argument is passed, it will be assigned the value "a," and the other two arguments will take their default values of 0. If two arguments are passed, they will be assigned to a and b, and c will take its default value. If all three arguments are passed, they will be assigned to a, b and c, respectively.

def add(a, b=0, c=0): 
   return a + b + c
print(add(2))

Output

The above code produces the following output

2

Example

def add(a, b=0, c=0): 
   return a + b + c
print(add(3,2))

Output

The above code produces the following output

5

Example

def add(a, b=0, c=0):
   return a + b + c
print(add(1,4,3))

Output

The above code produces the following output

8

Example

Another way to achieve function overloading in Python is by using variable- length arguments. Here's an example −

def add(*args):
   result = 0
   for arg in args:
      result += arg
   return result
print(add(1,2,3))

Output

The above code produces the following output

6

Example

def add(*args):
   result = 0
   for arg in args:
      result += arg
   return result 
print(add(1,3,4,5))

Output

The above code produces the following output

13

In this example, the function add takes a variable number of arguments. All the arguments are packed into a tuple named args, and the function adds up all the values in the tuple and returns the result.

By using default arguments and variable-length arguments, we can create functions that behave differently depending on the number and type of arguments that are passed to them, which is the essence of function overloading.

Example

Overloading a function with different parameter types.

In this example, the function multiply is overloaded to accept two different types of parameters: int and float. The function checks the type of the arguments and performs the multiplication only if they are of the same type. If the types are different, the function returns an error message.

def multiply(a, b):
   if isinstance(a, int) and isinstance(b, int):
      return a * b
   elif isinstance(a, float) and isinstance(b, float): 
      return a * b
   else:
      return "Invalid argument types" 
print(multiply(2, 3))

Output

The above code produces the following output

6

Example

def multiply(a, b):
    if isinstance(a, int) and isinstance(b, int): 
       return a * b
    elif isinstance(a, float) and isinstance(b, float):
       return a * b
    else:
       return "Invalid argument types"
print(multiply(2.5, 3.5))

Output

The above code produces the following output

8.75

Example

def multiply(a, b):
   if isinstance(a, int) and isinstance(b, int): 
      return a * b
   elif isinstance(a, float) and isinstance(b, float):
      return a * b
   else:
       return "Invalid argument types"
print(multiply(2, 3.5))

Output

The above code produces the following output

Invalid argument types

Example

Overloading a function with different number of parameters

In this example, the function add is overloaded with two different numbers of parameters. However, Python does not allow function overloading based on the number of parameters alone, and the second definition of add will overwrite the first one. Therefore, when we try to call add with only two arguments, we get a TypeError because the function expects three arguments.

def add(a, b): 
   return a + b
def add(a, b, c): 
   return a + b + c
print(add(2, 3))

Output

The above code produces the following output

Traceback (most recent call last):
  File "/home/cg/root/42648/main.py", line 5, in 
    print(add(2, 3))
TypeError: add() missing 1 required positional argument: 'c'

Example

def add(a, b): 
   return a + b

def add(a, b, c): 
   return a + b + c
print(add(2,3,4))

Output

The above code produces the following output

9

Thus, in this article, we have seen different ways to achieve function overloading in Python.


Advertisements