Polymorphism
Polymorphism allows different classes to be used through the same interface. Objects of different types can be treated uniformly.
💻 Method Overriding
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
# Polymorphism in action
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(f"Area: {shape.area()}")🔄 Duck Typing
# If it walks like a duck and quacks like a duck, it's a duck
class Duck:
def speak(self):
return "Quack"
class Person:
def speak(self):
return "Hello"
def make_it_speak(thing):
print(thing.speak())
make_it_speak(Duck()) # Quack
make_it_speak(Person()) # Hello🎯 Key Takeaways
- Polymorphism: Same interface, different implementations
- Method overriding: Child redefines parent method
- Duck typing: Type determined by behavior, not inheritance
- Abstract classes: Base classes with required methods
- Interfaces: Define method signatures