📘 Lesson 20 · Intermediate

Python Inheritance

Learn class inheritance, method overriding, super(), and polymorphism.

What is Inheritance?

Inheritance lets a new class (the child or subclass) automatically get all methods and attributes of an existing class (the parent or base class). You can then add new behaviour or override existing methods. This avoids duplicating shared code across similar classes, and allows different objects to respond to the same method call in their own way — a concept called polymorphism.

Basic Inheritance and Overriding

Write the parent class name in parentheses after the child class name. When a child class has a method with the same name as the parent, the child's version takes priority — this is called overriding.

animals.py
class Animal:
    def __init__(self, name): self.name = name
    def speak(self): print(f"{self.name} makes a sound")

class Dog(Animal):
    def speak(self): print(f"{self.name}: Woof!")  # override

class Cat(Animal):
    def speak(self): print(f"{self.name}: Meow!")  # override

# Polymorphism — same method, different behaviour
for a in [Dog("Rex"), Cat("Mimi"), Animal("Bird")]:
    a.speak()
▶ Output
Rex: Woof!
Mimi: Meow!
Bird makes a sound

super() — Calling the Parent

super() calls the parent class's method. Use it when you want to extend parent behaviour rather than completely replace it. Always call super().__init__() in the child constructor to ensure the parent's setup runs first.

super.py
class Vehicle:
    def __init__(self, make, model):
        self.make = make; self.model = model

class Car(Vehicle):
    def __init__(self, make, model, doors):
        super().__init__(make, model)  # parent setup first
        self.doors = doors             # then extra attribute
    def __str__(self):
        return f"{self.make} {self.model} ({self.doors}-door)"

c = Car("Toyota", "Corolla", 4)
print(c)
print(isinstance(c, Vehicle))  # Car IS-A Vehicle
▶ Output
Toyota Corolla (4-door)
True
Keep class hierarchies shallow — 2 to 3 levels maximum. Deep hierarchies become difficult to follow and debug. Prefer composition over deep inheritance.

🧠 Quick Check

Which function calls the parent class __init__?

parent()
base()
super()
inherit()

Tags

inheritancesuper()overridepolymorphismbase classchild class