What is the difference between overloading and overriding in Python?

What is the difference between overloading and overriding in Python?

a) Overloading involves redefining methods in a subclass, while overriding involves defining methods with the same name but different signatures
b) Overriding involves redefining methods in a subclass, while overloading involves defining methods with the same name but different signatures
c) Overloading and overriding are the same in Python
d) Overloading applies to variables, while overriding applies to methods

Answer:

b) Overriding involves redefining methods in a subclass, while overloading involves defining methods with the same name but different signatures

Explanation:

Overriding in Python occurs when a subclass redefines a method inherited from a parent class, providing a new implementation while maintaining the same method name and signature. Overloading, on the other hand, refers to defining multiple methods with the same name but different signatures (number or type of parameters). Python does not natively support method overloading, but you can achieve similar functionality using default arguments or by checking argument types within a method.

# Example of Overriding
class Parent:
    def greet(self):
        print("Hello from Parent")

class Child(Parent):
    def greet(self):
        print("Hello from Child")

# Overloading not natively supported, but can be simulated
def add(a, b=0):
    return a + b

print(add(1, 2))  # Output: 3
print(add(1))     # Output: 1

In the example above, overriding is demonstrated with the greet() method in the Child class. For overloading, Python uses default arguments to handle different numbers of parameters.

Overriding is useful for customizing inherited behavior, while overloading (or its equivalent) allows for flexible method signatures.

Leave a Comment

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

Scroll to Top