Interview question
What is polymorphism and how does it work? Polymorphism क्या है और कैसे काम करता है?
Answer
# Method Overriding (Compile-time Polymorphism)
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# Polymorphic behavior
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(shape.area()) # Different implementation
# Duck Typing (Runtime Polymorphism)
class Dog:
def sound(self):
return 'Woof!'
class Cat:
def sound(self):
return 'Meow!'
class Bird:
def sound(self):
return 'Tweet!'
def animal_sound(animal):
print(animal.sound())
animal_sound(Dog()) # Woof!
animal_sound(Cat()) # Meow!
animal_sound(Bird()) # Tweet!
# 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 __str__(self):
return f'({self.x}, {self.y})'
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2 # Uses __add__
print(v3) # (4, 6)# Method Overriding
class Parent:
def method(self):
print('Parent')
class Child(Parent):
def method(self):
print('Child')
obj = Child()
obj.method() # Child
# Duck Typing - same method, different objects
def fly(obj):
obj.fly() # Works if object has fly() method
# Operator Overloading
class MyClass:
def __add__(self, other):
# Custom + behaviorWas this answer clear?