Think of inheritance like a family recipe book. You have your grandmother's basic bread dough (the parent). When you want to make rye bread, you don't rewrite the whole process from scratch; you start with her base recipe and add caraway seeds (the subclass). In Python, this means one class can borrow all the setup code and behaviours of another.
Why it matters: Imagine building a game. You need
Player, Enemy, and NPC classes. They all have health, position, and movement logic. Inheritance lets you define that shared logic once in a base class so your code stays clean.The syntax
class Vehicle:
def __init__(self, make):
self.make = make
# Car is a subclass of Vehicle
class Car(Vehicle):
passCar inherits everything from Vehicle. You don't need to write any code inside the body.The parentheses
(Vehicle) tell Python that Car is a specialised type of Vehicle. Because it inherited, you can create a car without worrying about how its make is stored—that logic already exists in the parent.Extending behaviour
class Vehicle:
def __init__(self, make):
self.make = make
class Car(Vehicle):
# Car adds doors to the parent's setup
def __init__(self, make, doors=4):
# Run Vehicle's __init__ first
super().__init__(make)
self.doors = doors
civic = Car('Honda', 2)
print(civic.make) # Honda (from Vehicle)
print(civic.doors) # 2 (Car's own)super().__init__(make) ensures the base class does its job first.Here,
Car adds a new piece of data (doors) but still needs the parent's logic for make. super() reaches the parent class, here Vehicle, so super().__init__(make) runs Vehicle's __init__, and the make gets stored. Using super() is like saying: "Do your part first, then I'll add my extras." The next lesson covers super() in full.Type checking
class Vehicle:
def __init__(self, make):
self.make = make
class Car(Vehicle):
pass
civic = Car('Honda')
print(isinstance(civic, Vehicle)) # True
print(type(civic) == Vehicle) # Falseisinstance checks if an object fits the category; type is exact.A car is a vehicle, so
isinstance returns True. But its specific type is still Car. This distinction helps when you want to accept any kind of transport in a function but need to know exactly what you're holding.