Method Overloading in Python

In this article, let us look at Method Overloading in Python.

Method Overloading:

Method Overloading is a form of Compile time polymorphism. In the case of method overloading, multiple methods belonging to the same class can have the same method name but different number of signatures/ arguments.

Method overloading can be used to add more to the behavior of the concerned methods. A user will not require more than one class to implement it.

NOTE:

Note that Python does not support method overloading. A user may overload 
all of the methods, but they will only be able to use the
lastest defined method.

Example

Approach:

  • Create a class say MethodOverloading
  • Inside the class, create a function say multiply which accepts two numbers as arguments and prints the multiplication result of those two numbers.
  • Create another function with the same name say multiply which accepts three numbers as arguments and prints the multiplication result of those three numbers.
  • Create an object for the above MethodOverloading() class.
  • Pass two numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • Pass three numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say MethodOverloading
class MethodOverloading:
   # Create a function say multiply which accepts two numbers as arguments 
   # and prints the multiplication result of those two numbers
   def multiply(self, x, y):
       print(x*y)
   # Create another function with the same name say multiply which accepts three 
   # numbers as arguments and prints the multiplication result of those three numbers
   def multiply(self, x, y, z):
       print(x*y*z)

# Create an object for the above MethodOverloading() class      
obj =MethodOverloading()
# Pass two numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3))
# Pass three numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3, 4))

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-7d5007590dae> in <module>
14 # Pass two numbers as arguments to the multiply() function and apply it
15 # on the above object and print the result
---> 16 print(obj.multiply(2, 3))
17 # Pass three numbers as arguments to the multiply() function and apply it
18 # on the above object and print the result

TypeError: multiply() missing 1 required positional argument: 'z'

Explanation:

Python does not support method overloading because Python always uses the last defined method. We can still overload methods in Python, but it’s pointless. However, method overloading can be implemented in Java, C++, and other languages in the manner described above.

Another way to perform method overloading in Python is as follows:

Approach:

  • Create a class say MethodOverloading.
  • Create a function say multiply which accepts two numbers as arguments and prints the multiplication result of those two numbers based on conditions.
  • Check if both the numbers are not equal to None using the if conditional statement, and operator.
  • If it is true then return the multiplication of both the numbers.
  • Else if Check only the first number passed is not None using the elif conditional statement.
  • If it is true then return only the first number.
  • Else return 0.
  • Create an object for the above MethodOverloading() class.
  • Call the above multiply() function without passing any arguments and print the result.
  • Call the above multiply() function by passing only one number as an argument and print the result.
  • Call the above multiply() function by passing two numbers as arguments and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say MethodOverloading
class MethodOverloading:
    # Create a function say multiply which accepts two numbers as arguments 
    # and prints the multiplication result of those two numbers based on conditions
    def multiply(self, a = None, b = None):
        # Check if both the numbers are not equal to None using the if conditional 
        # statement, and operator
        if a!= None and b!= None:
            # If it is true then return the multiplication of both the numbers
            return  a*b
        # else if Check only the first number passed is not None using the elif conditional statement
        elif a!= None:
            # If it is true then return only the first number
            return a
        else:
            # Else return 0
            return 0

# Create an object for the above MethodOverloading() class  
class_object = MethodOverloading()

# Call the above multiply() function without passing any arguments and print the result
print("Result = ", class_object.multiply())
# Call the above multiply() function by passing only one number as an argument and print the result
print("Result = ", class_object.multiply(3))
# Call the above multiply() function by passing two numbers as arguments and print the result
print("Result = ", class_object.multiply(4, 5))

Output:

Result = 0
Result = 3
Result = 20

Advantages of Method overloading

  • Reduces complexities and improves code quality
  • Method overloading is also used for reusability and easy accessibility.
  • Using Python method overloading, you can make multiple methods appear logically as a single method. For example, we have only one method – get area – that 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 improves the readability of the code, making it easier for the programmer to write code and increasing the programmer’s efficiency.
  • We can also keep backward compatibility by using method overloading. What does this imply? If we have a method that performs complex calculations, we could add a new requirement to it that allows it to perform the same complex calculation with minor changes. If we add a new parameter (optional parameter), its presence will be used to perform calculations in either the old or new way.

Method overloading In Brief

  • Same method name but different number of arguments.
  • Inheritance is not required(optional).
  • It is an example of compile time polymorphism.
  • It is performed between methods within the class.
  • Overloading can be done within a class
  • Method Overloading is used to add more to the behavior of methods.
  • Static methods can be overloaded here.
  • It is related with Polymorphism concept of OOPs.

Method overloading allows you to call the same method in multiple ways. All of the methods will have the same name, but there may be three differences:

  • The number of parameters could vary.
  • The data type of arguments
  • The order of the parameters