What is the difference between overloading and overriding in Python?
Answer:
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.