Back to Study Material Python

Inheritance

Inheritance allows one class to acquire the attributes and methods of another class. The class being inherited from is called the parent or base class. The...

Inheritance

How Inheritance Works in Python Classes

Inheritance allows one class to acquire the attributes and methods of another class. The class being inherited from is called the parent or base class. The class that inherits is called the child or derived class. This mechanism lets you reuse existing code, extend functionality, and build logical hierarchies that mirror real-world relationships.

In Python, you specify inheritance by putting the parent class name inside parentheses after the child class name:

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

def describe(self): return f"{self.make} {self.model}"

class Car(Vehicle): def __init__(self, make, model, doors): super().__init__(make, model) self.doors = doors

def describe(self): return f"{super().describe()} with {self.doors} doors"

my_car = Car("Toyota", "Camry", 4) print(my_car.describe()) # Toyota Camry with 4 doors

The super() function gives you access to the parent class. Calling super().__init__() runs the parent's __init__, so you do not have to duplicate that setup code. The child class then adds its own attribute, doors, on top.

Python supports multiple inheritance, meaning a class can inherit from more than one parent. This is powerful but can create ambiguity when two parents define the same method. Python resolves this using the Method Resolution Order, which you can inspect with ClassName.__mro__. It searches classes from left to right and bottom to top in the hierarchy.

Inheritance is best used when there is a genuine "is-a" relationship. A Car is a Vehicle, so inheritance makes sense. If the relationship is "has-a" (a Car has an Engine), prefer composition instead, where you store the Engine as an attribute rather than inheriting from it.

Exam tip: Know the difference between super() used with and without arguments. In Python 3, super() with no arguments is the preferred form and works correctly in most situations. The older Python 2 style required passing the class and self explicitly.