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 behaviors 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
class Car(Vehicle): # 'Car' is a subclass of '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 specialized 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 behavior
class Vehicle:
def __init__(self, make):
self.make = make
class Car(Vehicle):
def __init__(self, make, doors=4): # Adds 'doors' to the parent's setup
super().__init__(make) # Calls Vehicle.__init__
self.doors = doors
civic = Car('Honda', 2)
print(civic.make) # Honda (from parent)
print(civic.doors) # 2 (specific to child)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. Using super() is like saying: "Do your part first, then I'll add my extras."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) # False (it's specifically a Car)isinstance 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.