Method Overloading In Python

Introduction

So you are building software that has to calculate the average of two integers. You wish to make a function or method for it to make it more readable. You just write a function that calculates an average of two integers.

However, you will find afterward in the software that you must also calculate the average of three numbers. Alternatively, you can require a function that can calculate the average of any parameters specified. 

To calculate the average of any number specified by the user, you have two options:

The first one is to create functions like – avg_two (to average 2 numbers), avg_three (to average 3 numbers), avg_four (to average 4 numbers), avg_float (to average float values), and so on.

The other option is to create a single multi-function that accepts a variable number of arguments or datatypes and performs your operation based on the parameters you specify.

What is a convenient option? Undoubtedly the second one.

Why remember all of those distinct function names? In fact, why do you want to build so many separate functions with various names?

Now you must be thinking, is it even feasible? With a similar name, many functions with various inputs? Yes, It’s known as method overloading in python. Read this article to understand more about method overloading in python.

Method Overloading

Now we understand that there is no need to make different functions that do the task just because you have multiple arguments.

You would use this:

def avg(a1: int, b1: int):

    …

def avg(a1: int, b1: int, c1: int):

    …

def avg(a1: float, b1: float):

    …

than this:

def avg_two(a1, b1):

    …

def avg_three(a1, b1, c1):

    …

def avg_float(a1, b1):

    …

Method overloading allows you to call the same method several times. For example, we can call the same function average with multiple numbers of arguments.

 

How to define method overloading?

Method overloading is a characteristic of OOPS languages that allow us to have two or more methods with the same name but distinct arguments that they accept as input values. To be more explicit, the settings can be changed in three ways:

  • The range of parameters might vary. As in the example of function overloading, one function requires two integers to calculate the average, while another requires three integers to calculate the average.
  • The data type of the arguments can differ. The function average takes either integers or float values as input, according to its specification.
  • The third method to modify the parameters is to change the order of the parameters.

Python Method Overloading

Now the question is, does python support method overloading? Unlike other languages, you cannot implement method overloading in Python by utilizing the same method name. Why?  

Method overloading in Python by using a similar method name. Why?

Python interprets everything as an object, including classes and methods.

There are two ways of method overloading in Python.

 

1: Using the same methods differ depending on the data type of the parameters

To accomplish method overloading in python, we make a single function that uses numerous parameters to execute the same purpose.

For example:

class multiply:

    def i_multiply (self, a1 = None, b1 = None, c1 = None):

        p = 0

        if a1 != None and b1 != None and c1 != None:

            p = a1 * b1 * c1

        else if a1 != None and b1 != None:

            p =  a1 * b1

        return p

We used three variables as input in the code; however, their default values are None. This implies that if we only give two values when using the function, the third will be heeded as None by default, and the result will just be the multiplication of the two numbers given as input.

So, this is a function that can take two or three arguments as input and exhibits the same method overloading characteristics.

  1. Method Overloading in Python Using Multipledispatch

We have seen how to offer method overloading features to a function by setting arguments = None, but there is a better approach. The multiple dispatch module can be used to give your functions method overloading characteristics in Python.

We will build many functions with a similar name, and we will put a function decorator directly above the function.

Add a Function Decorator

@<decorator_name>  

# using the decorator above the function def

def function(..):

Here’s how we will utilize the decorators for the functions to have the characteristics of method overloading:

from multi dispatch import dispatch

@dispatch(int, int) 

def sum(a1, b1):

    return a1 b1

 

@dispatch(int, int, int)

def sum(a1, b1, c1):

    return a1 b1 c1

@dispatch(double, double, double)  # initializing parameters as double

def sum(a1, b1, c1):

    return a1 b1 c1

Here we will understand that the names of all the functions are the same, and we can use different parameter datatype method overloading using the decorators.

print(sum(72.1, 35.4, 59.6))

print(sum(5, 4))

print(sum(1, 4, 4))

Output:

152119.464

9

9

So, in this case, we just used the sum function with different parameters. The decorator has defined the data types for each function definition, which is dynamically dispatched based on the data types and the number of parameters we specified in the decorator.

The term dispatch means to transmit; thus, when the functions are called, the decorator transmits these definitions dynamically.

Constructor Overloading in Java

In Java, constructor overloading refers to the use of multiple constructors in an instance class. Each overloaded constructor, however, must have a unique signature. For the compilation to succeed, each constructor must have a unique set of parameters.

Inheritance in Python

In object-oriented programming, python inheritance is a powerful feature. It refers to creating a new class with minimal or no changes to an existing class. The new class is known as the derived (or child) class, and the one it inherits from is known as the base (or parent) class.

Benefits of Method Overloading in Python

  • Using Python method overloading, we can create several methods that look logically as a single method. For example, in get_perimeter methods, we have only one method get_perimeter – that can be used to find the perimeter of shapes based on the inputs given to the function showing logically as a single method. This improves the readability, making it simpler for the developer to develop code, and improves the programmer’s efficiency.
  • We can also keep backward compatibility if we utilize the overloading method. This means that If you have a method that does difficult calculations, we add a requirement to it that allows it to execute the same complex computation with few modifications. If we introduce a new parameter, its presence will be utilized to do computations in the old or new manner.
  • Method overloading in Python also helps code reusability.

Conclusion

Method overloading in python is a critical methodology, and the method is extremely effective in complicated circumstances requiring condition-based use and execution of certain parameters. The methodology must be implemented properly to eliminate redundant parameter use.

UNext Jigsaw is offering courses in Data Science and Machine Learning with a guaranteed placement feature. You should definitely consider pursuing a Data Science online course!

 

Related Articles

loader
Please wait while your application is being created.
Request Callback