Inheritance lets one class (a "subclass") reuse and extend the behavior of another class (a "base class" or "parent class"), instead of rewriting shared logic from scratch. Polymorphism means different classes can be used through the same interface — you call the same method name on different objects, and each one responds in its own way. Together, they're the backbone of most object-oriented Python code.
Program to Demonstrate Inheritance and Polymorphism
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement speak()")
def describe(self):
return f"{self.name} says {self.speak()}"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class Cow(Animal):
def speak(self):
return "Moo!"
animals = [Dog("Rex"), Cat("Whiskers"), Cow("Bessie")]
for animal in animals:
print(animal.describe())
Output:
Rex says Woof!
Whiskers says Meow!
Bessie says Moo!
Dog, Cat, and Cow all inherit from Animal — written as class Dog(Animal): — which means each one automatically gets the __init__ constructor and the describe() method without rewriting them. Each subclass only needs to define what's actually different about it: its own version of speak().
The loop at the bottom is where polymorphism shows up: it calls animal.describe() on every object the exact same way, without checking "is this a Dog or a Cat?" first. Python figures out which speak() to actually run based on the real type of each object at runtime — Dog's version for the Dog instance, Cat's version for the Cat instance, and so on. This is also called "duck typing" in Python: if an object has the method you're calling, Python doesn't care what class it technically belongs to.
Raising NotImplementedError inside the base class's speak() is a common pattern for marking a method as something every subclass is required to override — if you forgot to implement speak() on a new subclass, you'd get a clear error the moment you tried to use it, rather than silently wrong behavior.
