Welcome back, programmer! In Module One, you learned what Object Oriented Programming is. You learned about objects and classes. In Module Two, you learned how to write classes and create objects in Python. You learned about __init__, self, attributes, and methods.
Now imagine you want to create a program about animals. You have dogs, cats, and birds. They all have names and ages. They all eat and sleep. But dogs can bark. Cats can meow. Birds can fly. Do you want to write the same code for name, age, eat, and sleep three times? That would be a lot of work.
This is where inheritance comes in. Inheritance lets one class get all the data and methods from another class. Then you can add new things or change things. It saves time and keeps your code organised.
We will also learn about polymorphism. Polymorphism means “many forms”. It lets different objects respond to the same action in their own way. A dog barks. A cat meows. Both respond to “make a sound”, but in different ways.
By the end of this module, you will be able to create parent classes and child classes. You will understand how to reuse code. You will see how polymorphism makes programs flexible. Let’s begin!
After you finish this module, you will be able to:
super() function to call the parent’s methods.Tunde lived in Ibadan. His father owned a car workshop. One day, Tunde asked his father, “Papa, how do you build different types of cars? You have taxis, buses, and private cars. They are all different, but they all have wheels and engines.”
His father smiled. “That is a good question,” he said. “We start with a basic design. Every car has wheels, an engine, and a steering wheel. That is the parent design. Then, for a taxi, we add a taxi sign and a meter. For a bus, we add many seats. For a private car, we add comfortable seats.”
Tunde understood. “So the basic design is like a parent class,” he said. “And the taxi, bus, and private car are like child classes. They inherit from the parent, but they add their own special things.”
His father nodded. “Exactly! And here is the amazing part. If we need to change the engine design, we only change it in the parent design. All the child designs get the update automatically. That saves us a lot of work.”
Tunde was excited. He decided to learn more about inheritance. He wanted to write code that reused ideas, just like his father’s workshop.
Moral of the story: Inheritance lets you build on what you already have. You write common things once in a parent class, and child classes get them for free.
Definition: Inheritance is when one class gets the attributes and methods of another class.
Why it is important: It saves time. You write common code once, and reuse it many times.
Simple explanation: Imagine you have a recipe for bread. You can use that recipe to make different types of bread: white bread, brown bread, and banana bread. You do not need to write the basic bread recipe again. You just add the special ingredients.
Real-life example: A smartphone inherits from a basic phone. It can call and text (from the basic phone), but it can also take photos and browse the internet.
School example: A science student inherits from a student. They have a name and age (from student), but they also study science subjects.
Home example: A puppy inherits from a dog. It has fur and a tail (from dog), but it is smaller and drinks milk.
Nigerian example: A danfo bus inherits from a vehicle. It has wheels and an engine (from vehicle), but it also has yellow paint and a conductor.
Illustration:
Parent Class: Vehicle
|
V
+--------+ +--------+ +--------+
| Car | | Bus | | Danfo |
+--------+ +--------+ +--------+
Child Classes inherit from Vehicle
Mini summary: Inheritance lets one class get the data and actions of another class. It saves time and keeps code organised.
Definition: A parent class is the class being inherited from. A child class is the class that inherits.
Why it is important: You need to know the difference to use inheritance correctly.
Simple explanation: The parent class is like a mother. The child class is like her child. The child gets some things from the mother, but also has its own things.
Real-life example: A vehicle is a parent class. A car is a child class.
School example: A person is a parent class. A student is a child class.
Home example: An animal is a parent class. A dog is a child class.
Nigerian example: A trader is a parent class. A food trader is a child class.
Illustration:
Parent Class: Animal
|
V
Child Class: Dog
|
V
Dog inherits from Animal
Mini summary: A parent class is inherited from. A child class inherits. The child gets things from the parent.
Definition: Inheritance creates an “is-a” relationship. A child class “is a” type of parent class.
Why it is important: It helps you know when to use inheritance.
Simple explanation: A dog “is an” animal. A car “is a” vehicle. A student “is a” person.
Real-life example: A smartphone “is a” phone.
School example: A science student “is a” student.
Home example: A puppy “is a” dog.
Nigerian example: A danfo “is a” vehicle.
Illustration:
Dog IS-A Animal ✓ Car IS-A Vehicle ✓ Student IS-A Person ✓ Dog IS-A Car ✗ (not correct)
Mini summary: Inheritance creates an “is-a” relationship. If the child “is a” type of parent, inheritance makes sense.
Definition: A parent class is a normal class that other classes will inherit from.
Why it is important: It holds the common code that all child classes will share.
Simple explanation: You write a class with common attributes and methods. Then child classes can use them.
Real-life example: A parent class called Animal with name and age.
School example: A parent class called Person with name and age.
Home example: A parent class called Appliance with brand and power.
Nigerian example: A parent class called Vehicle with wheels and engine.
Example code:
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(self.name + " is eating.")
def sleep(self):
print(self.name + " is sleeping.")
Illustration:
class Animal:
__init__ -> name, age
eat() -> "eating"
sleep() -> "sleeping"
Mini summary: A parent class holds common attributes and methods. Child classes will inherit them.
Definition: A child class inherits from a parent class. You write the parent class name in parentheses.
Why it is important: Child classes get all the parent’s attributes and methods for free.
Simple explanation: You write class Dog(Animal):. The (Animal) means Dog inherits from Animal.
Real-life example: A child class called Dog inherits from Animal.
School example: A child class called ScienceStudent inherits from Student.
Home example: A child class called SmartPhone inherits from Phone.
Nigerian example: A child class called Danfo inherits from Vehicle.
Example code:
class Dog(Animal):
def bark(self):
print(self.name + " is barking.")
Illustration:
class Animal:
name, age
eat(), sleep()
|
V
class Dog(Animal):
bark()
Dog inherits eat and sleep from Animal
Mini summary: A child class inherits from a parent by writing the parent’s name in parentheses.
Definition: You can add new methods to a child class that the parent does not have.
Why it is important: It lets the child class do things that are special to it.
Simple explanation: A dog can bark. An animal cannot bark. So bark() is added only to the Dog class.
Real-life example: A smartphone can take photos. A basic phone cannot.
School example: A science student can do experiments. A normal student cannot.
Home example: A smart TV can browse the internet. A normal TV cannot.
Nigerian example: A danfo can carry many passengers. A private car cannot.
Example code:
class Dog(Animal):
def bark(self):
print(self.name + " is barking.")
my_dog = Dog("Bingo", 3)
my_dog.eat() # inherited from Animal
my_dog.bark() # added in Dog
Output:
Bingo is eating. Bingo is barking.
Illustration:
Animal: eat(), sleep() Dog: eat(), sleep() + bark()
Mini summary: Child classes can add new methods. These are special actions that only the child can do.
Definition: Overriding means changing a method in the child class that already exists in the parent class.
Why it is important: Sometimes the child needs to do something differently.
Simple explanation: The parent says “eat”. The child says “eat differently”.
Real-life example: A baby eats milk. An adult eats rice. Both “eat”, but differently.
School example: A JSS1 student studies basic maths. A JSS3 student studies harder maths. Both “study”, but differently.
Home example: A puppy sleeps a lot. An adult dog sleeps less. Both “sleep”, but differently.
Nigerian example: A small trader sells from a tray. A big trader sells from a shop. Both “sell”, but differently.
Example code:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(self.name + " makes a sound.")
class Dog(Animal):
def speak(self):
print(self.name + " barks.")
class Cat(Animal):
def speak(self):
print(self.name + " meows.")
my_dog = Dog("Bingo")
my_cat = Cat("Fluffy")
my_dog.speak() # Bingo barks.
my_cat.speak() # Fluffy meows.
Illustration:
Animal.speak() -> "makes a sound" Dog.speak() -> "barks" Cat.speak() -> "meows"
Mini summary: Overriding means changing a method in the child class. The child does it differently.
super() to Call the ParentDefinition: super() is a function that lets you call a method from the parent class.
Why it is important: Sometimes you want to use the parent’s method and then add more.
Simple explanation: You say “do what the parent does, then do this extra thing”.
Real-life example: A child says “Thank you” like their parent, then adds “sir” or “madam”.
School example: A student follows the school rules, then adds their own study rules.
Home example: You follow your family recipe, then add your own spice.
Nigerian example: You follow your mother’s jollof recipe, then add your own special pepper.
Example code:
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print("I am " + self.name + " and I am " + str(self.age) + " years old.")
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def introduce(self):
super().introduce()
print("I am a " + self.breed + ".")
my_dog = Dog("Bingo", 3, "Labrador")
my_dog.introduce()
Output:
I am Bingo and I am 3 years old. I am a Labrador.
Illustration:
Dog.__init__
|
V
super().__init__(name, age) -> sets name and age
|
V
self.breed = breed -> sets breed
Mini summary: super() lets you call the parent’s method. You can use it and then add more.
Definition: Polymorphism means “many forms”. It lets different objects respond to the same action in their own way.
Why it is important: It makes programs flexible. You can write one piece of code that works with many types of objects.
Simple explanation: If you say “speak” to a dog, it barks. If you say “speak” to a cat, it meows. Same action, different results.
Real-life example: If you press “play” on a phone, it plays music. If you press “play” on a video player, it plays video.
School example: If you say “write” to a student, they write with a pen. If you say “write” to a computer, it writes on the screen.
Home example: If you say “cook” to a microwave, it heats food. If you say “cook” to a cooker, it boils food.
Nigerian example: If you say “sell” to a food trader, they sell food. If you say “sell” to a cloth trader, they sell cloth.
Illustration:
Action: speak()
|
V
+--------+ +--------+ +--------+
| Dog | | Cat | | Cow |
| barks | | meows | | moos |
+--------+ +--------+ +--------+
Same action, different results!
Mini summary: Polymorphism means “many forms”. Different objects can respond to the same action in their own way.
Definition: You can use polymorphism by calling the same method on different objects.
Why it is important: It lets you write flexible code.
Simple explanation: You write a loop that goes through a list of animals. You call speak() on each one. Each animal speaks in its own way.
Real-life example: A remote control has a “power” button. It works on the TV, the fan, and the air conditioner.
School example: A teacher says “introduce yourself”. Each student says their own name.
Home example: You say “clean” to your broom, your mop, and your vacuum. Each cleans differently.
Nigerian example: You say “cook” to your pot, your pan, and your oven. Each cooks differently.
Example code:
animals = [Dog("Bingo"), Cat("Fluffy"), Cow("Buttercup")]
for animal in animals:
animal.speak()
Output:
Bingo barks. Fluffy meows. Buttercup moos.
Illustration:
for animal in animals:
animal.speak()
|
V
Dog.speak() -> barks
Cat.speak() -> meows
Cow.speak() -> moos
Mini summary: Polymorphism lets you call the same method on different objects. Each object responds in its own way.
Definition: You can use inheritance and polymorphism together.
Why it is important: This is the power of OOP.
Simple explanation: You create a parent class with a method. Child classes override the method. Then you can use polymorphism to call the method on any child.
Real-life example: A vehicle parent class has a move() method. Cars, buses, and bikes override it.
School example: A person parent class has a study() method. Science, art, and commercial students override it.
Home example: An appliance parent class has a work() method. Fridge, fan, and cooker override it.
Nigerian example: A trader parent class has a sell() method. Food, cloth, and phone traders override it.
Example code:
class Vehicle:
def __init__(self, name):
self.name = name
def move(self):
print(self.name + " is moving.")
class Car(Vehicle):
def move(self):
print(self.name + " is driving on the road.")
class Boat(Vehicle):
def move(self):
print(self.name + " is sailing on the water.")
class Plane(Vehicle):
def move(self):
print(self.name + " is flying in the sky.")
vehicles = [Car("Toyota"), Boat("Canoe"), Plane("Boeing")]
for v in vehicles:
v.move()
Output:
Toyota is driving on the road. Canoe is sailing on the water. Boeing is flying in the sky.
Illustration:
Vehicle.move()
|
V
Car.move() -> driving
Boat.move() -> sailing
Plane.move() -> flying
Mini summary: Inheritance and polymorphism work together. The parent defines the method. The children override it. Polymorphism calls it on any child.
Definition: Inheritance is best when there is an “is-a” relationship and shared code.
Why it is important: Using inheritance wrongly makes code confusing.
Simple explanation: Use inheritance when the child “is a” type of parent and they share common things.
Real-life example: A car “is a” vehicle. Use inheritance. A car “has an” engine. Do not use inheritance; use an attribute.
School example: A student “is a” person. Use inheritance. A student “has a” bag. Do not use inheritance.
Home example: A dog “is an” animal. Use inheritance. A dog “has a” collar. Do not use inheritance.
Nigerian example: A danfo “is a” vehicle. Use inheritance. A danfo “has a” conductor. Do not use inheritance.
Illustration:
IS-A relationship -> Use inheritance HAS-A relationship -> Use attribute Dog IS-A Animal -> inheritance Dog HAS-A Collar -> attribute
Mini summary: Use inheritance for “is-a” relationships. Use attributes for “has-a” relationships.
Definition: There are different ways classes can inherit from each other.
Why it is important: Knowing the types helps you design your classes.
Simple explanation: You can have single inheritance (one parent), multilevel inheritance (parent, child, grandchild), and multiple inheritance (many parents).
Real-life example: A grandfather, a father, and a son are multilevel inheritance.
School example: A person, a student, and a science student are multilevel inheritance.
Home example: An appliance, a kitchen appliance, and a fridge are multilevel inheritance.
Nigerian example: A vehicle, a bus, and a luxury bus are multilevel inheritance.
Table: Types of Inheritance
| Type | Description | Example |
|---|---|---|
| Single | One parent, one child | Animal → Dog |
| Multilevel | Parent → Child → Grandchild | Animal → Dog → Puppy |
| Multiple | Many parents, one child | Flyer + Swimmer → Duck |
Illustration:
Single: Animal
|
Dog
Multilevel: Animal
|
Dog
|
Puppy
Mini summary: There are different types of inheritance: single, multilevel, and multiple. Start with single inheritance.
Definition: These are mistakes beginners often make.
Why it is important: Knowing them helps you avoid them.
Simple explanation: Here are some mistakes to watch out for.
List of mistakes:
super().__init__().super() when needed.Illustration:
Bad Inheritance Good Inheritance +----------------+ +----------------+ | Car IS-A Engine| | Car IS-A Vehicle| | (wrong) | | (correct) | +----------------+ +----------------+
Mini summary: Avoid common mistakes. Use inheritance only for “is-a”. Always call super().__init__().
Definition: You will now combine inheritance and polymorphism in one program.
Why it is important: This is how real OOP programs work.
Simple explanation: Create a parent class. Create child classes. Override methods. Use a loop to call the same method on all objects.
Real-life example: A zoo program with different animals.
School example: A school program with different types of students.
Home example: A smart home program with different appliances.
Nigerian example: A market program with different types of traders.
Example code:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(self.name + " makes a sound.")
def eat(self):
print(self.name + " is eating.")
class Dog(Animal):
def speak(self):
print(self.name + " barks.")
class Cat(Animal):
def speak(self):
print(self.name + " meows.")
class Cow(Animal):
def speak(self):
print(self.name + " moos.")
animals = [Dog("Bingo"), Cat("Fluffy"), Cow("Buttercup")]
for animal in animals:
animal.eat()
animal.speak()
print("---")
Output:
Bingo is eating. Bingo barks. --- Fluffy is eating. Fluffy meows. --- Buttercup is eating. Buttercup moos. ---
Illustration:
Animal (parent)
|
V
+--------+ +--------+ +--------+
| Dog | | Cat | | Cow |
| speak | | speak | | speak |
| barks | | meows | | moos |
+--------+ +--------+ +--------+
All inherit eat() from Animal
Mini summary: You can combine inheritance and polymorphism. One parent class, many child classes, and one loop to call them all.
| Word | Simple Definition |
|---|---|
| Inheritance | When one class gets the data and actions of another class. |
| Parent class | The class being inherited from. |
| Child class | The class that inherits. |
| Override | Changing a method in the child class. |
| super() | A function that calls the parent’s method. |
| Polymorphism | “Many forms” – different objects respond to the same action differently. |
| Is-a relationship | When a child “is a” type of parent. |
| Has-a relationship | When a class “has a” thing as an attribute. |
| Single inheritance | One parent, one child. |
| Multilevel inheritance | Parent → Child → Grandchild. |
| Multiple inheritance | Many parents, one child. |
| Reuse | Using code again. |
class ParentName:.__init__ with common attributes.class ChildName(ParentName):.super() to call parent methods.super() can call any method, not just __init__?super() calls the parent’s method.super().__init__().super() when needed.super().__init__() in the child.
Create Parent Class
|
V
Create Child Classes
|
V
Override Methods
|
V
Create Objects
|
V
Loop and Call Same Method
|
V
Polymorphism! 🎉
Module 1: What is OOP? Module 2: Classes and Objects Module 3: Inheritance and Polymorphism Module 4: Encapsulation and Abstraction Module 5: Putting It All Together
| Feature | Parent Class | Child Class |
|---|---|---|
| Also called | Base class | Derived class |
| What it has | Common attributes and methods | Common + special attributes and methods |
| Example | Animal | Dog |
| Inherits from | Nothing | Parent |
| Feature | Inheritance | Polymorphism |
|---|---|---|
| What it does | Reuses code | Many forms |
| Relationship | Is-a | Same action, different results |
| Example | Dog inherits Animal | Dog barks, Cat meows |
| Key word | class Dog(Animal): | Same method name |
Lesson 1: Inheritance lets one class get the data and actions of another class.
Lesson 2: A parent class is inherited from. A child class inherits.
Lesson 3: Inheritance creates an “is-a” relationship.
Lesson 4: A parent class holds common attributes and methods.
Lesson 5: A child class inherits by writing the parent’s name in parentheses.
Lesson 6: Child classes can add new methods.
Lesson 7: Overriding means changing a method in the child class.
Lesson 8: super() calls the parent’s method.
Lesson 9: Polymorphism means “many forms”.
Lesson 10: Polymorphism lets you call the same method on different objects.
Lesson 11: Inheritance and polymorphism work together.
Lesson 12: Use inheritance for “is-a” relationships.
Lesson 13: There are different types of inheritance: single, multilevel, and multiple.
Lesson 14: Avoid common mistakes. Use inheritance wisely.
Lesson 15: You can combine inheritance and polymorphism in one program.
In this module, you learned about inheritance and polymorphism. You learned that inheritance lets one class get the data and methods of another class. You learned about parent classes and child classes. You learned about the “is-a” relationship. You learned how to create a parent class and a child class. You learned how to add new methods and override existing ones. You learned how to use super() to call the parent’s method. You learned what polymorphism is and how it lets different objects respond to the same action in their own way. You also learned when to use inheritance and how to avoid common mistakes. You are now ready for Module Four, where you will learn about encapsulation and abstraction.
class Child(Parent):.super()? A function that calls the parent’s method.super().Match the word to its meaning.
| Word | Meaning |
|---|---|
| 1. Inheritance | A. Changing a method in the child class |
| 2. Parent class | B. When one class gets data and actions from another |
| 3. Child class | C. The class being inherited from |
| 4. Override | D. The class that inherits |
| 5. Polymorphism | E. “Many forms” |
Answers: 1-B, 2-C, 3-D, 4-A, 5-E
Animal. You want to create a class Dog that inherits from it. How do you write it? (class Dog(Animal):)Dog to have a bark() method. Where do you add it? (In the Dog class)Dog to speak differently from Animal. What do you do? (Override the speak() method)__init__ from the child. What do you use? (super().__init__())speak())Title: Build a Family of Classes
Instructions: In groups of 3, choose a parent class (e.g., Vehicle, Animal, Person). Create two child classes. Add at least one new method and override one method. Create objects and call the methods. Present to the class.
Title: My First Inheritance
Instructions: Write a parent class called Shape with a method area(). Create two child classes: Circle and Square. Override area() in each. Create objects and call area(). Write down what happens.
Title: A Zoo Program
Instructions: Create a parent class Animal with name and age. Create child classes Dog, Cat, and Cow. Override speak() in each. Create a list of animals. Loop through the list and call speak() and eat(). Print the results.
Task: Write a short paragraph (5 sentences) explaining what you learned about inheritance and polymorphism. Then, list three things you found easy and one thing you found hard. Finally, describe the parent class and child classes you created.
super() calls the parent’s method.In Module Four, we will learn about encapsulation and abstraction. You will learn how to hide data and show only what is needed. You will learn how to protect your objects. To get ready, make sure you:
See you in Module Four! 🚀
End of Module Three · Object Oriented Programming