Method Overloading in Python

Learn via video courses
Topics Covered

Overview

Method overloading is essentially a feature of object-oriented languages, in which we can have two or more methods functions that have the same name but the parameters that they take as input values are different.

We cannot perform method overloading in python however, we can make our code have the same features as that of overloaded functions by making simple changes to the Python code.

Introduction to Overloading in Python

So you're writing a program where you need to multiply some two given numbers. You want to write a function/method for it, to increase readability. Easy, you create a function that multiplies two numbers.

But later in the program, you realize you need to multiply 3 numbers as well. Or maybe even further down the lane, you need a function that can multiply any number of arguments given!

Well, if you see from a user's perspective, they might want to multiply two numbers, or maybe 3, or 4, and so on. It can even happen that at a point you might not just want to multiply two numbers, it could even be two floats or a float and a number.

Now let me give you two options. The first, is to create multiple functions like - multi_two (to multiply 2 numbers), multi_three (to multiply 3 numbers), multi_four (to multiply 4 numbers), multi_float (to multiple floats), and so on, or you could create just one function named multi, that is capable of taking a different number of parameters or data types and that performs your task depending on what input you give in as parameters.

What seems like a more convenient option? Of course the second one! Why would you want to remember all those different function names? Or, for that matter, why would you want to create so many functions with different names in the first place?

Now you might ask, is that even possible? Multiple functions with different inputs with the same name? YES! It's called method overloading.

What is Method Overloading?

As we read above, you need not create multiple functions that do the same job just because you have a different set of parameters, or different parameters altogether.

You'd rather do this:

than this:

Why? It would be extremely cumbersome to create new functions with different names that perform the same operations, with just a different number or type of parameters.

Method overloading is a means by which you can call the same method in different ways, i.e. with different parameters based on the number of arguments or their different datatypes. Just like we did above, we call the same function, Mul with different number of parameters.

All the story of not creating multiple functions, understood. But how do we define method overloading?

Method overloading is essentially a feature of object oriented languages, in which we can have two or more methods (functions) that have the same name but the parameters that they take as input values are different. To be more specific, there can be 3 changes done to the parameters:

  • The number of parameters could be different. As in our example above, one function takes 2 integers to multiply, and another takes 3 integers to multiply.
  • The data type of the parameters could be different. Our function Mul can either take integers, or the other definition of our function states that it can also take floats as input.
  • The third way the parameters could be changed is by changing the order of parameters.

To successfully overload a method, it is important that the methods should have the same name. For example, you want to calculate the area of different shapes, and for every shape, you have different data types to store their dimensions (like Circle data type to store the radius, or Square data type to store the side, or Rect data type to store 2 integers - length and breadth).

Here's how your code could look like(assuming that the above data types have been defined):

This code is not in python, just a general function definition is written to give an idea of how method overloading could look like.

What kind of overloading is this? Here, the only thing changing is the data type of parameters of the functions.

Python Method Overloading

Now you may have already seen how we perform method overloading, but let's get deep into it's specifics and take a look at mistakes we must avoid, and also how we can perform method overloading in Python.

Earlier in this article, we read about method overloading being a feature of most object oriented programming languages. Python too, supports OOPs. So, now in python if you wanted to create a class "Addition" so that you could get the sum of as many numbers as you like with your "my_sum" function, you know how to make it. Here's how you might make your class look like:

Now if you wanted to call any of these functions, you need to first instantiate an object of this class "Addition".

Here, the variable obj is now an object of the class Addition. If we want to call any function, we do it like this:

Let's test these functions to see if our overloading worked.

Output:

Huh? Why the error?

In python, unlike other languages, you cannot perform method overloading by using the same method name. Why?

Everything is an object in python, classes, and even methods. Say you have an object Addition, which is a class (everything in python is an object, so the class Addition is an object too). It has an attribute called - my_sum. It's the only attribute that the class Addition can have with that name.

So when you're writing def my_sum(...): ... you have essentially created a object, which here is a method and you are assigning it to the "my_sum" attribute of class Addition. If you write two definitions, then the second definition replaces the first one, just the way that assignment always behaves.

Like in our example above, there are two functions with the same name - my_sum. The second function replaces the first one, and that is why the only valid function that you can call is my_sum that takes 3 parameters as input.

Instead, to perform the same function, i.e. to achieve method overloading, we create a single function that takes multiple parameters. After doing that, all you need to do is check the number of parameters taken as input.

In the code above, we put 3 variables as input, but their default values are None. Which means that while calling the function if we enter just two values, the third will be considered None by default and hence the output will just be the sum of the two integers given as input.

So essentially this is a function with the capability of taking two or three parameters as input, and it also shows the same features of method overloading.

However, this is not the most efficient method to perform method overloading, as you might see in the example above. We have if elif statements, in such a simple code for a function that just returns the sum of 3 inputs (which can also be None). What if you increased the number of inputs you wanted? How many if elif statements would you write then?

If your function was more complex than this one, it is highly likely that you would get stuck writing if elif statements to achieve the features of method overloading in your function, and that makes this method, not the best one. So what is the better way?

Method Overloading in Python Using Multipledispatch

We saw how to provide the functionality of method overloading to a function by setting parameters = None, however, there's another better way of doing so. The module: multipledispatch can be used for giving your functions the features of method overloading in python. (to install the module run this command - pip3 install multipledispatch in the terminal)

We will create multiple functions with the same name, and just above the function, we'll add a function decorator. (For reference - Function decorators are powerful tools in python. By using them we can modify the behavior of a function or a class.)

How to Add a Function Decorator?

Back to method overloading in Python using MultiDispatch, we wrap another function in the same class, in order to extend the behavior of the wrapped function without modifying it permanently.

If you do not understand decorators, google and read more about them, or if you do not wish to, don't worry, you have already understood method overloading. Go on to read some advantages of the same.

Here's how we will use the decorators so that the functions have the features of method overloading:

Did you see that the names of all the functions were the same? We're able to perform different parameter datatype method overloading using the above decorators.

Output:

So here, just like how we previously called the my_sum function, we have called the mul function simply, and gave it different parameters this time. The decorator has now defined the data types for every function definition is dynamically dispatched according to the data types we mentioned, as well as the number of parameters we mentioned in the decorator.

The word dispatch simply means send, so the decorator is sending these definitions (the ones we defined using the decorator) dynamically to the functions when they are called.

Advantages of Method Overloading in Python

  • Using python method overloading you can make more than one method appear as a single method logically. For example, our get_area methods, we have just one method - get_area which can be used to calculate the area of different shapes depending on the type of input given to the function while still presenting itself logically as one method. This increases the readability of the code, and makes it easier for the programmer and also increases the efficiency of the programmer to write code.
  • If we use method overloading, we can also preserve backward compatibility. What does that mean? If we have a method, that performs complex calculations we could give it a new requirement so that it could optionally perform the same complex calculation, but with slight changes. If we add a new parameter (optional parameter) then the presence of that parameter will be used to perform calculations in either the old way or the new way.
  • Method overloading in Python improves the code reusability as well.

There! You now know all about method overloading in Python. Let's summarize all the points discussed in the article:

Conclusion

  • Method overloading is a means by which you can call the same method in different ways. All the methods will have the same name, but can have 3 differences:
    • The number of parameters could be different
    • The data type of parameters
    • Order of parameters
  • Specifically in Python, you cannot perform method overloading. However, there are two means by which you can achieve the same functionality:
    • Optional parameters. When you provide optional parameters, you will have to check in the code and perform the calculations / algorithm accordingly
    • Use the multidispatch module that will help in defining the data types of the parameters, and will allow you to create multiple methods with the same name
  • The few main advantages of method overloading in Python are:
    • Making more than one method appear as a single method logically
    • Preserve backward compatibility.
    • We are able to achieve code reusability, and so it saves memory.