What is method overloading and does Python support it?

What is method overloading and does Python support it?

a) Method overloading allows multiple methods with the same name but different signatures, and Python supports it directly
b) Method overloading allows multiple methods with the same name but different signatures, but Python does not support it directly
c) Method overloading allows a method to be called multiple times, and Python supports it directly
d) Method overloading is the same as method overriding, and Python supports it directly

Answer:

b) Method overloading allows multiple methods with the same name but different signatures, but Python does not support it directly

Explanation:

Method overloading is a concept where multiple methods can have the same name but different signatures (different number or types of parameters). Python does not support method overloading directly, unlike some other programming languages. Instead, Python handles method calls based on the number of arguments or by using default arguments and variable-length argument lists.

class MathOperations:
    def add(self, a, b=0, c=0):
        return a + b + c

# Creating an object of MathOperations class
math_ops = MathOperations()
print(math_ops.add(1))       # Output: 1
print(math_ops.add(1, 2))    # Output: 3
print(math_ops.add(1, 2, 3)) # Output: 6

In this example, the add method uses default arguments to simulate overloading. Depending on the number of arguments passed, it can add two or three numbers.

Even though Python does not support method overloading directly, you can achieve similar functionality using default parameters and *args for variable-length arguments.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top