Full answer
python
class Employee:
def __init__(self, name, salary):
self.name, self.salary = name, salary
def annual_pay(self):
return self.salary * 12
def describe(self):
return f"{self.name} earns {self.annual_pay():,}"
class Manager(Employee):
def __init__(self, name, salary, bonus):
super().__init__(name, salary)
self.bonus = bonus
def annual_pay(self):
return super().annual_pay() + self.bonus
staff = [Employee("Tom", 50_000), Manager("Asha", 90_000, 200_000)]
for s in staff:
print(s.describe(), isinstance(s, Employee), type(s).__name__)
print(Manager.__mro__)Output:
text
Tom earns 600,000 True Employee
Asha earns 1,280,000 True Manager
(<class '__main__.Manager'>, <class '__main__.Employee'>, <class 'object'>)Manager.__init__ reuses the parent's setup through super() and adds bonus. annual_pay extends the parent's calculation instead of copying it. describe is defined only on Employee, yet for Asha it calls the overridden annual_pay, which is polymorphism. __mro__ shows the lookup order Python uses: Manager, Employee, object. Prefer composition when the relationship is 'has a' rather than 'is a', and keep hierarchies shallow so behaviour stays easy to trace.
python
class Employee:
def __init__(self, name, salary):
self.name, self.salary = name, salary
def annual_pay(self):
return self.salary * 12
def describe(self):
return f"{self.name} earns {self.annual_pay():,}"
class Manager(Employee):
def __init__(self, name, salary, bonus):
super().__init__(name, salary)
self.bonus = bonus
def annual_pay(self):
return super().annual_pay() + self.bonus
staff = [Employee("Tom", 50_000), Manager("Asha", 90_000, 200_000)]
for s in staff:
print(s.describe(), isinstance(s, Employee), type(s).__name__)
print(Manager.__mro__)Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Subclasses inherit and override
- super() calls the next class in the MRO
- Overrides are used by inherited methods
- isinstance respects inheritance
- Prefer composition for has-a
Common mistakes
- Copying parent code instead of calling super()
- Deep inheritance hierarchies
Follow-ups
- How does the MRO work with multiple inheritance?
- When would you choose composition?
Tips
- Show super() in __init__