Advanced level · Module 1: Object-Oriented Programming in Python · Lesson 2 of 4
Inheritance and Composition
Reuse behaviour by extending classes or by combining objects, and know when each fits.
In this lesson you will
- Create a subclass and call super()
- Prefer composition when an object 'has a' rather than 'is a'
Key concepts
inheritancesuper()method overridingcomposition
The lesson
Inheritance lets a class extend another: Staff(Person) gets everything a Person has and adds a salary. Use it for true 'is a' relationships — a staff member is a person.
Composition means an object contains other objects: an Organisation has a list of people. It is usually more flexible than inheritance, because parts can be changed without rewriting a class hierarchy.
super().__init__(...) calls the parent class's set-up from a subclass, so shared attributes are set in one place.
Step by step
- Write a Person class with name and phone.
- Write Staff and Volunteer subclasses with their own attributes.
- Write an Organisation class that holds a list of people.
- Add a method that reports staff and volunteer counts.
Practice activity
Model Staff and Volunteer as subclasses of Person, and an Organisation class that is composed of a list of people.
Expected result: A working model where Organisation reports staff and volunteer counts.
Check your understanding
-
Is a Shop 'a' Product list or does it 'have a' product list?
Show answer
It has one, so composition fits.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.