Interview question
What is method overriding and method overloading? Method overriding और method overloading क्या है?
Answer
# Method Overriding - same method name, different implementation
class Parent:
def method(self):
print('Parent method')
class Child(Parent):
def method(self):
print('Child method')
super().method() # Call parent
child = Child()
child.method()
# Output:
# Child method
# Parent method
# Method Overloading - Python doesn't support like Java
# But can achieve with default arguments or *args
class Calculator:
# Using default arguments
def add(self, a, b, c=0):
return a + b + c
print(Calculator().add(2, 3)) # 5
print(Calculator().add(2, 3, 4)) # 9
# Using *args
def multiply(self, *args):
result = 1
for num in args:
result *= num
return result
print(Calculator().multiply(2, 3)) # 6
print(Calculator().multiply(2, 3, 4)) # 24
# Using type checking
def process(self, data):
if isinstance(data, int):
return data * 2
elif isinstance(data, str):
return data.upper()
elif isinstance(data, list):
return len(data)
# Operator Overloading
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __str__(self):
return f'({self.x}, {self.y})'
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # (4, 6)
print(v1 == v2) # False# Method Overriding
class Parent:
def method(self):
print('Parent')
class Child(Parent):
def method(self):
print('Child')
# Method Overloading (using *args)
def func(self, *args):
if len(args) == 1:
# Do something
elif len(args) == 2:
# Do something else
# Operator Overloading
def __add__(self, other):
# Custom + operatorWas this answer clear?