w3resource

What is method overloading in Python?

Understanding method overloading in Python

Unlike some other programming languages like Java or C++, Python does not support method overloading in the traditional sense. You can have multiple methods with the same name but different parameter types or counts.

If your language supports method overloading, you could have something like:

void sum_nums(int num) {
    // do something
}
void sum_nums(double num) {
    // do something different
}

However, in Python, only the latest defined method is recognized. This is because Python uses dynamic typing, and method names are not directly tied to their parameter lists.

Python keeps only the last method defined if there are multiple methods with the same name but different parameters. The earlier ones will be overwritten.

Example-1: Demonstration of how Python defines methods with the same name

Code:

class MyClass:    
    def sum_nums(self, x, y):
        print("Sum of two numbers", x + y)
    def sum_nums(self, x, y, z):
        print("Sum of three numbers", x + y + z)
obj = MyClass()
obj.sum_nums(1, 2, 3)  # Output: 6

In the example above, only the method sum_nums(self, x, y, z) is recognized, and the earlier defined sum_nums(self, x, y) is overwritten.

Example-2:

Code:

class MyClass:    
    def sum_nums(self, x, y):
        print("Sum of two numbers", x + y)    
    def sum_nums(self, x, y, z):
        print("Sum of three numbers", x + y + z)
obj = MyClass()
obj.sum_nums(1, 2)

The above example through the error "TypeError: sum_nums() missing 1 required positional argument: 'z'" as If multiple methods with the same name but different parameters exist in Python, only the last method is kept.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/what-is-method-overloading-in-python.php