Inheritance
Inheritance lets you create a new class from an existing one. The new child class gets all the attributes and methods of the parent class and can add or change behaviour, so you write shared code once.
A parent and child class
Put the parent class in brackets after the child's name. The child inherits everything it doesn't redefine.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def describe(self):
return f"{self.name} earns KES {self.salary:,}"
def annual_pay(self):
return self.salary * 12
class Intern(Employee):
def annual_pay(self):
return self.salary * 3 # internships last three months
wambui = Employee("Wambui", 80000)
lulu = Intern("Lulu", 20000)
print(wambui.describe(), "|", wambui.annual_pay())
print(lulu.describe(), "|", lulu.annual_pay())
Intern didn't define __init__ or describe(), so it used Employee's versions. It did define its own annual_pay(), which overrides the parent's. Python looks for a method on the object's own class first, then moves up to the parent.
Extending the parent with super()
Often a child needs everything the parent does plus a little more. super() gives you access to the parent's methods, so you can reuse them instead of copying code.
class Manager(Employee):
def __init__(self, name, salary, team_size):
super().__init__(name, salary) # let Employee set name and salary
self.team_size = team_size # then add the new attribute
def describe(self):
basic = super().describe() # reuse the parent's sentence
return f"{basic} and leads {self.team_size} people"
odhiambo = Manager("Odhiambo", 150000, 6)
print(odhiambo.describe())
print(odhiambo.annual_pay())
Employee.If a child defines its own __init__ but forgets to call super().__init__(...), the parent's setup never runs. The object then has no name or salary, and the first method that uses them fails with AttributeError: 'Manager' object has no attribute 'name'.
Checking relationships
An object of a child class counts as an instance of the parent too. Inheritance models an "is a" relationship: a manager is an employee.
print(isinstance(odhiambo, Manager)) print(isinstance(odhiambo, Employee)) print(isinstance(wambui, Manager)) print(issubclass(Intern, Employee))
This means a function written for Employee objects works with managers and interns as well:
staff = [wambui, lulu, odhiambo]
total = sum(person.annual_pay() for person in staff)
print(f"Yearly wage bill: KES {total:,}")
Each object used its own version of annual_pay(). This idea is called polymorphism.
Inheritance chains and the object class
A child can itself have children (multi-level inheritance). Every class ultimately inherits from Python's built-in object class, which is where default behaviour such as the basic printout comes from. The method resolution order (MRO) shows the order in which Python searches classes for a method:
class SeniorManager(Manager):
pass
print([cls.__name__ for cls in SeniorManager.__mro__])
Multiple inheritance
Python allows a class to inherit from more than one parent. If two parents have a method with the same name, the one listed first wins, following the MRO.
class Swimmer:
def move(self):
return "swims"
class Flyer:
def move(self):
return "flies"
def altitude(self):
return "up to 100 m"
class Duck(Swimmer, Flyer):
pass
d = Duck()
print(d.move())
print(d.altitude())
print([cls.__name__ for cls in Duck.__mro__])
Multiple inheritance is powerful but can get confusing. A common, safe use is small "mixin" classes that each add one feature. When in doubt, keep to single inheritance.
Inheritance or composition?
Use inheritance only for genuine "is a" relationships. If the relationship is "has a" (a school has students; a car has an engine), store one object inside another instead. This is called composition, and it usually leads to simpler code than deep inheritance chains.
class Department:
def __init__(self, name):
self.name = name
self.staff = [] # a department HAS employees
def hire(self, employee):
self.staff.append(employee)
it = Department("IT")
it.hire(wambui)
it.hire(odhiambo)
print(it.name, [person.name for person in it.staff])
Key points
class Child(Parent):gives the child all of the parent's attributes and methods.- Define a method with the same name to override it; use
super()to reuse the parent's version. - Always call
super().__init__(...)when the child has its own__init__. isinstance()andissubclass()check relationships;__mro__shows the search order.- Use inheritance for "is a" and composition for "has a".
Tip: use the ← and → keys to move between pages.
