Method Overloading in Python with Example

Method overloading is one of the prominent features of many object-oriented programming languages, such as Java and C++.

It is a fundamental element of polymorphism that allows us to define two or more methods with the same name but with different parameter lists or signatures. These methods are called overloaded methods, or simply method overloading.

In method overloading mechanism, a method performs different operations or behaviors based on the passing of different sets of arguments.

When we overload a method, it improves the code readability and maintainability because we divide implementation into multiple methods instead of being concentrated in a single, complex one.

However, Python does not support method overloading entirely. This is because Python is a dynamically typed language and data type binding happens at runtime. This is called late binding.

It differs from static binding used in the programming languages, such as Java and C++. In static binding, overloaded methods are called or invoked at compile time based on the passing of arguments.

In Python, when we define multiple methods with the same name in a class, the last method definition overrides all the previous one and can only have the latest defined method. However, there will be no syntax error if we define two methods with the same name, but the last one will simply replace all the previous one. Let’s understand it with the help of example code.

Example 1:

class Addition:
    # Define a method to calculate the sum of two numbers.
    def sum(self, x, y):
        s = x + y
        print("Sum of two numbers: ", s)

    # Define a method overloading 'sum'.
    def sum(self, x, y, z):
        s = x + y + z
        print("Sum of three numbers: ", s)

# Outside class definition.
# Create an instance of class Addition.
obj = Addition()
# Calling methods by passing argument values.
obj.sum(20, 30, 40)
obj.sum(20, 30)
Output:
       Sum of three numbers:  90
       TypeError: Addition.sum() missing 1 required positional argument: 'z'

In this example, we have defined a class named Addition that contains overloaded methods ‘sum’. The first method calculates the sum of two numbers, while the second method calculates the sum of three numbers. Thus, both methods are overloaded because both have the same name but different parameter lists.

In this case, as we have called the first method, it generated an error name TypeError because the second method replaced the first one. In other words, the first method will be ignored and any reference to it will raise an error, as generated in the above output.

How to Implement Method Overloading in Python?


Even though Python doesn’t directly support method overloading in the same form as other object-oriented programming languages do. But Python provides alternative approaches to achieve the same functionality. In Python, we can achieve or implement method overloading using different ways. Here are the ways to achieve method overloading in Python:

1. Default Arguments:

This is the first method to achieve or implement method overloading in Python. However, this is not the perfect way of implementing method overloading, but it works. In this method, we set a default value to the arguments. Commonly, we set “None” or “0” value as a default value to the attribute.

We define a method with multiple parameters, and some of them have default values. Python will choose the method to execute based on the number of arguments passed during the function call. Look at the below example codes:


Example 2:

# Define a class named Addition.
class Addition:
    # Define a method named sum within the class.
    # This method accepts three arguments: a, b, and c, with 'c' having a default value of 0.
    def sum(self, a, b, c = 0):
        # This statement calculates the sum of these three numbers and returns the result.
        return a + b + c

# Outside the class definition.
# Create an instance of class Addition.
obj = Addition()

# Call overloaded methods by passing different sets of arguments and store them into variables.
result1 = obj.sum(5, 6)
result2 = obj.sum(5, 3, 9)

# Print the results.
print("Addition of two numbers: ", result1)
print("Addition of three numbers: ", result2)
Output:
       Addition of two numbers:  11
       Addition of three numbers:  17

In this example, we have defined sum() method with three arguments: a, b, and c, with c having a default value of 0. This default value will be used when we do not pass the third argument during the method call, as done in the first method call. During the second method call, we have passed three arguments to the method.

Example 3:

class Employee:
    def cal_totalSalary(self, bonus = None):
        if bonus is None:
            return (self.salary + self.allowances)
        else:
            return (self.salary + self.allowances + bonus)

# Create the first instance of class Employee.
emp1 = Employee()
emp1.salary = 40000
emp1.allowances = 12000
print("Total salary = ", emp1.cal_totalSalary())

# Create the second instance of class Employee.
emp2 = Employee()
emp2.salary = 60000
emp2.allowances = 12000
print("Total salary = ", emp2.cal_totalSalary(3000))
Output:
       Total salary =  52000
       Total salary =  75000

Example 3:

class MathOperations:
    def calculate(self, a, b, operation = None):
        if operation == "add":
            return a + b
        elif operation == "sub":
            return a - b
        elif operation == "multiply":
            return a * b
        elif operation == "div":
            return a / b
        else:
            return "Invalid operation or missing arguments."

# Create an instance of the MathOperations class.
obj = MathOperations()

# Perform different operations by passing different sets of arguments.
result1 = obj.calculate(5, 3, "add")
result2 = obj.calculate(5, 3, "sub")
result3 = obj.calculate(5, 3, "multiply")
result4 = obj.calculate(25, 5, "div")
result5 = obj.calculate(5, 3)

# Print the results.
print("Result 1:", result1)
print("Result 2:", result2)
print("Result 3:", result3)
print("Result 4:", result4)
print("Result 5:", result5)
Output:
       Result 1: 8
       Result 2: 2
       Result 3: 15
       Result 4: 5.0
       Result 5: Invalid operation or missing arguments.

In this example, we have defined a class named MathOperations. This class contains an overloaded calculate() method to perform different mathematical operations based on the provided operation argument. The calculate() method takes three parameters: a, b, and operation. However, the operation parameter has default value “None”.

Depending on the value of the operation parameter, the method performs different mathematical operations, including addition, subtraction, multiplication, and division. The method returns the result of the corresponding operation or an error message if the operation is missing or invalid.

2. Using Variable-Length Arguments:

This is another way to implement method overloading in Python. In this method, we use variable-length arguments. This approach allows a method to accept a variable number of arguments. We can use the *args parameter to achieve this. Let’s take an example based on this method.

Example 4:

class Calculator:
    def add(self, *args):
        return sum(args)

calc = Calculator()
result1 = calc.add(5, 4)
result2 = calc.add(5, 3, 6)

print(result1)
print(result2)
Output:
       9
       14

In this example, we have defined a class named Calculator. This class contains the add() method which can accept any number of arguments and returns their sum.

Advantages of Method Overloading in Python


Method overloading offers several advantages in Python. They are as:

  • Method overloading improves the code readability. It makes the code more readable by using the same method name for related operations.
  • It simplifies code maintenance easy. When we need to add new functionality, we can integrate with existing methods, reducing the need for extensive changes.
  • By overloading methods, we can reuse code effectively.
  • Method overloading enables us to call the same method with varying numbers of arguments, providing flexibility in the parameter list.

In this tutorial, we have discussed different ways to implement method overloading in Python with various example programs. Hope that you will have understood the basic concepts of implementing method overloading and practiced all programs. In the next, we will understand how to implement operator overloading in Python with the help of various advanced example programs.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love