Polymorphism with inheritance allows objects of different classes to be treated as objects of a common superclass. This enables a unified interface for different class types, promoting flexibility and code reusability.
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def animal_sound(animal):
print(animal.speak())
# Instances
dog = Dog()
cat = Cat()
# Polymorphic behavior
animal_sound(dog) # Output: Woof!
animal_sound(cat) # Output: Meow!
Animal): Defines a generic speak method.Dog, Cat): Override the speak method with specific implementations.animal_sound): Accepts any Animal type and calls the speak method, demonstrating polymorphism.class Shape:
def area(self):
raise NotImplementedError("Subclass must implement abstract method")
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
# Polymorphic function
def print_area(shape):
print(f"Area: {shape.area()}")
# Instances
circle = Circle(5)
square = Square(4)
# Polymorphic behavior
print_area(circle) # Output: Area: 78.5
print_area(square) # Output: Area: 16
Shape): Abstract method area is defined.Circle, Square): Implement the area method with specific calculations.print_area): Accepts any Shape type and calls area.