Topic 64 of 64
Class Inheritance
Overview
Inheritance lets a child class reuse and extend a parent class's attributes and methods. Python supports single and multiple inheritance. The super() function calls the parent's implementation without hardcoding the parent class name.
Syntax
python
class Animal:
def __init__(self, name: str) -> None:
self.name = name
def speak(self) -> str:
raise NotImplementedError
class Dog(Animal):
def speak(self) -> str:
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self) -> str:
return f"{self.name} says Meow!"
d = Dog("Rex")
d.speak() # "Rex says Woof!"
# Check inheritance
isinstance(d, Animal) # True
issubclass(Dog, Animal) # TrueCommon Pitfalls
- Always call super().__init__() in the child __init__ to properly initialize the parent class — omitting it can cause AttributeError.
- Python's MRO (Method Resolution Order) determines which parent method is called in multiple inheritance — use ClassName.__mro__ to inspect it.
- Interview tip: Python supports multiple inheritance (class C(A, B)) — but the 'diamond problem' is resolved via MRO (C3 linearization algorithm).
Real-World Example
Employee hierarchy using inheritance and super()
example
python
class Employee:
def __init__(self, name: str, salary: float) -> None:
self.name = name
self.salary = salary
def annual_compensation(self) -> float:
return self.salary * 12
class Manager(Employee):
def __init__(self, name: str, salary: float, bonus: float) -> None:
super().__init__(name, salary) # call parent __init__
self.bonus = bonus
def annual_compensation(self) -> float:
return super().annual_compensation() + self.bonus
mgr = Manager("Alice", 8000, 20000)
print(mgr.annual_compensation()) # 116000.0