Part 09 / Topic 5 of 12
Inheritance: single, multilevel, super(), overriding
Inheritance lets a new class reuse an existing class. The new class is the child (or subclass); the existing one is the parent (or base class). Write it as class Child(Parent):.
- The child gets all the parent's attributes and methods for free.
- Method overriding: the child writes a method with the same name to do it its own way.
super().__init__(...)calls the parent's__init__, so you do not repeat the setup code.- Single inheritance: one parent. Multilevel: a chain, such as
Director→Manager→Employee.
Think of a family recipe: the child keeps the recipe and adds a twist.
Real-world example: staff in an office.
class Employee:
def __init__(self, name: str, salary: int):
self.name = name
self.salary = salary
def role(self) -> str:
return "Employee"
def describe(self) -> str:
return f"{self.name} | {self.role()} | ₹{self.salary:,}"
class Manager(Employee): # single inheritance
def __init__(self, name: str, salary: int, team_size: int):
super().__init__(name, salary) # parent sets name and salary
self.team_size = team_size # extra attribute
def role(self) -> str: # overriding
return f"Manager of {self.team_size}"
class Director(Manager): # multilevel: Director -> Manager -> Employee
def role(self) -> str:
return "Director, " + super().role() # extend the parent's version
print(Employee("Asha", 40000).describe())
print(Manager("Ravi", 90000, 5).describe())
print(Director("Neha", 250000, 40).describe())
Output:
Asha | Employee | ₹40,000
Ravi | Manager of 5 | ₹90,000
Neha | Director, Manager of 40 | ₹250,000
(The , format groups digits in thousands, not in the Indian lakh style.)
describe() is written once in Employee, but each object calls its own role().
class Employee: ...
class Manager(Employee): ...
boss = Manager()
print(isinstance(boss, Employee)) # True (a Manager is an Employee)
print(issubclass(Manager, Employee)) # True
print(issubclass(Employee, Manager)) # False
🔍 Going deeper: every class inherits from
objecteven if you do not write it. That is where default methods such as__init__,__str__and__eq__come from.
Done here? The practice set for Part 9 — 8 exercises with solutions — is on the part page.