Hello, amazing coder! You have learned so much already – variables, loops, lists, functions, and modules. Now, we are going to enter the world of objects and classes. This is how big programs are built in the real world!
Think about your favorite video game. It has characters, weapons, and levels. Each character has a name, health, and abilities. In programming, we can create a class as a blueprint for a character. Then we make many objects from that blueprint – each with their own name and health.
We will also learn how to save data to files – so your programs can remember things even after you turn off the computer!
By the end of this module, you will be able to create your own objects and save data to files. You will feel like a real software engineer building complex systems. Let’s go!
After this module, you will be able to:
Kofi loved football. He wanted to create a computer program to manage his team. He had players with names, jersey numbers, and positions. He thought, “I need a way to represent a player in my program.”
His older sister, a software engineer, explained: “You can create a class called ‘Player’. The class is like a form – it has fields for name, jersey, and position. Then you can create many objects – one for each player – by filling in the form.”
Kofi also wanted to save the team data so he could load it later. His sister showed him how to save to a file – like writing the team list in a notebook.
Now Kofi could create any number of players, save the team, and load it back – just like a real football manager!
Let’s learn how to do the same in Python!
Definition: An object is a thing that has properties (data) and actions (functions). It represents something from the real world.
Why is it important? Objects help us model real‑world things in code – like a car, a person, or a bank account.
Simple explanation: Think of a toy car. It has a color, a size, and it can move forward and backward. That’s an object!
Real‑life example: Your phone is an object – it has a brand, a screen size, and it can call and text.
School example: A student is an object – they have a name, a class, and they can study.
Home example: A chair is an object – it has a color, material, and you can sit on it.
Nigerian example: A bus (danfo) is an object – it has a color, a number of seats, and it can transport passengers.
Illustration:
+-----------------+
| Car Object |
+-----------------+
| Properties: |
| - each dress made is an object.
Illustration:
+---------------------------+
| Class: Player |
+---------------------------+
| Properties: |
| - name |
| - jersey_number |
| - position |
+---------------------------+
| Actions: |
| - score_goal() |
| - pass_ball() |
+---------------------------+
|
v
+---------------------------+
| Object 1: "Kofi" |
| jersey: 10, forward |
+---------------------------+
| Object 2: "Ama" |
| jersey: 5, defender |
+---------------------------+
Mini summary: A class is a blueprint; an object is a specific example made from that blueprint.
📘 Lesson 3: Defining a Class in Python
Definition: In Python, you define a class using the class keyword, followed by the class name.
Why is it important? This is how you create your own blueprint for objects.
Simple explanation: You write class Player: and then indent the properties and actions.
Real‑life example: You write the blueprint for a house – rooms, doors, windows.
School example: The school has a class called “Student” – every student is an object.
Home example: You define a class “Book” – each book has a title and author.
Nigerian example: A bank defines a class “Customer” – each customer is an object.
Illustration:
class Player:
def __init__(self, name, jersey):
self.name = name
self.jersey = jersey
def display(self):
print("Player: " + self.name + ", Jersey: " + str(self.jersey))
Mini summary: Use class to define a blueprint. The __init__ method sets up the object.
📘 Lesson 4: Creating Objects (Instances)
Definition: Creating an object from a class is called instantiation. You use the class name like a function.
Why is it important? This is how you actually create usable objects in your program.
Simple explanation: You take the cookie cutter and press it into the dough – that makes a cookie (object).
Real‑life example: You use the car blueprint to build a specific car – that’s creating an object.
School example: The school registers a new student – that creates a student object.
Home example: You bake a cake using the recipe – that creates a cake object.
Nigerian example: A bank opens a new account – that creates a customer object.
Illustration:
player1 = Player("Kofi", 10)
player2 = Player("Ama", 5)
player1.display() # Player: Kofi, Jersey: 10
player2.display() # Player: Ama, Jersey: 5
Mini summary: You create objects by calling the class name with the required data.
📘 Lesson 5: Attributes – The Data of an Object
Definition: Attributes are the variables that belong to an object. They hold the object’s data.
Why is it important? Attributes store the state of an object – like a player’s name and jersey.
Simple explanation: A car has attributes like color, model, and speed.
Real‑life example: A phone has attributes – brand, screen size, battery life.
School example: A student has attributes – name, age, class.
Home example: A pet has attributes – name, breed, age.
Nigerian example: A bank account has attributes – account number, balance, owner name.
Illustration:
class Dog:
def __init__(self, name, breed):
self.name = name # attribute
self.breed = breed # attribute
dog1 = Dog("Bingo", "German Shepherd")
print(dog1.name) # Bingo
print(dog1.breed) # German Shepherd
Mini summary: Attributes are the data that each object stores.
📘 Lesson 6: Methods – The Actions of an Object
Definition: Methods are functions that belong to an object. They define what the object can do.
Why is it important? Methods allow objects to perform actions – like a player scoring a goal.
Simple explanation: A car has methods – accelerate, brake, turn.
Real‑life example: A phone has methods – call, send_text, take_photo.
School example: A student has methods – study, take_exam.
Home example: A remote control has methods – turn_on, turn_off, change_channel.
Nigerian example: A bank account has methods – deposit, withdraw, check_balance.
Illustration:
class Player:
def __init__(self, name, goals):
self.name = name
self.goals = goals
def score(self):
self.goals = self.goals + 1
print(self.name + " scored! Total: " + str(self.goals))
kofi = Player("Kofi", 0)
kofi.score() # Kofi scored! Total: 1
kofi.score() # Kofi scored! Total: 2
Mini summary: Methods are actions that objects can perform.
📘 Lesson 7: The __init__ Method – The Constructor
Definition: __init__ is a special method that runs automatically when you create a new object. It initialises (sets up) the object’s attributes.
Why is it important? It ensures every object starts with the correct data.
Simple explanation: It’s like filling out a form when you register – you provide your name and other details.
Real‑life example: When you buy a phone, it comes with a charger and manual – that’s initialisation.
School example: When a new student joins, they fill out a registration form – that’s __init__.
Home example: When you get a new pet, you give it a name and register it at the vet.
Nigerian example: Opening a bank account – you provide your name, address, and ID.
Illustration:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
self.speed = 0 # default value
car1 = Car("Toyota", "Camry")
print(car1.make) # Toyota
print(car1.speed) # 0
Mini summary: __init__ is the setup method that runs when you create an object.
📘 Lesson 8: Inheritance – Reusing Code with Parent Classes
Definition: Inheritance allows a new class to borrow (inherit) attributes and methods from an existing class.
Why is it important? It promotes reusability – you don’t have to write everything from scratch.
Simple explanation: A “Car” class is a parent. A “ElectricCar” class can inherit from Car – it gets all the car features, plus extra ones.
Real‑life example: All phones have a screen and battery. A “Smartphone” inherits from “Phone” and adds apps.
School example: A “Student” is a person. “Teacher” is also a person – they both inherit from “Person”.
Home example: A “Dog” and a “Cat” both inherit from “Pet”.
Nigerian example: A “Account” class – “SavingsAccount” and “CurrentAccount” inherit from it.
Illustration:
class Pet:
def __init__(self, name):
self.name = name
def eat(self):
print(self.name + " is eating.")
class Dog(Pet):
def bark(self):
print(self.name + " says woof!")
dog1 = Dog("Bingo")
dog1.eat() # Bingo is eating. (inherited)
dog1.bark() # Bingo says woof! (own method)
Mini summary: Inheritance lets a child class reuse code from a parent class.
📘 Lesson 9: Why Use Objects and Classes?
Definition: Objects and classes help you organise code in a way that mirrors the real world.
Why is it important? They make large programs easier to manage and understand.
Simple explanation: Instead of having many separate variables, you group related data and actions into objects.
Real‑life example: A game with many characters – each is an object with health, position, and abilities.
School example: A school management system – students, teachers, classes are all objects.
Home example: A smart home system – lights, thermostats, and doors are objects.
Nigerian example: A banking app – customers, accounts, and transactions are objects.
Illustration:
+-----------------------+
| Without Objects |
+-----------------------+
| player1_name = "Kofi" |
| player1_goals = 0 |
| player2_name = "Ama" |
| player2_goals = 0 |
+-----------------------+
+-----------------------+
| With Objects |
+-----------------------+
| player1 = Player("Kofi", 0) |
| player2 = Player("Ama", 0) |
+-----------------------+
Mini summary: Objects help organise code by grouping related data and actions.
📘 Lesson 10: Reading from a File
Definition: Reading from a file means getting data that is stored on your computer’s hard drive.
Why is it important? Files store data permanently – even after you turn off the computer.
Simple explanation: Like reading a book – you open it and read the words.
Real‑life example: A game loads your saved progress from a file.
School example: Your teacher opens a file to view your grades.
Home example: You open a recipe file to read the instructions.
Nigerian example: A bank opens a file to load customer data.
Illustration:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
Mini summary: Use open() with "r" to read from a file.
📘 Lesson 11: Writing to a File
Definition: Writing to a file means saving data from your program to a file on the computer.
Why is it important? You can save user data, game progress, or any information for later.
Simple explanation: Like writing in your notebook – you put the words on paper.
Real‑life example: You save a document in Word – it writes to a file.
School example: You write your homework in a file and save it.
Home example: You write a shopping list and save it on your phone.
Nigerian example: A bank writes transaction details to a file.
Illustration:
file = open("data.txt", "w")
file.write("Hello, this is a saved file.")
file.close()
Mini summary: Use open() with "w" to write to a file.
📘 Lesson 12: Appending to a File
Definition: Appending means adding new data to the end of an existing file.
Why is it important? You can keep adding to a file without losing the old data.
Simple explanation: Like adding new pages to a notebook – the old pages stay.
Real‑life example: You add a new contact to your phone’s contact list file.
School example: The teacher adds new grades to the class record file.
Home example: You add a new item to your shopping list file.
Nigerian example: A bank appends each transaction to a log file.
Illustration:
file = open("data.txt", "a")
file.write("\nNew line added.")
file.close()
Mini summary: Use "a" mode to append data to a file.
📘 Lesson 13: Closing Files – Why It’s Important
Definition: Closing a file means telling the computer you are done using it. This frees up resources.
Why is it important? If you don’t close files, you might lose data or cause errors.
Simple explanation: Like closing a book after you finish reading – it’s polite and helps keep things tidy.
Real‑life example: You close a document after editing to save your changes.
School example: You close your notebook when the lesson is over.
Home example: You close the fridge door to keep food fresh.
Nigerian example: A shopkeeper closes the cash register after counting.
Illustration:
file = open("data.txt", "r")
content = file.read()
file.close() # Always close the file!
Mini summary: Always close files with .close() to save data and free resources.
📘 Lesson 14: Saving and Loading Game Data
Definition: You can save game progress (like level, score, lives) to a file and load it later.
Why is it important? Players can continue where they left off!
Simple explanation: Like saving your place in a book with a bookmark.
Real‑life example: Many video games have a “Save Game” feature.
School example: You save your essay draft to work on it later.
Home example: You save your favorite TV show episodes to watch later.
Nigerian example: A football game saves the team lineup and scores.
Illustration:
# Save
file = open("save.txt", "w")
file.write("Level:3, Lives:5, Score:1200")
file.close()
# Load
file = open("save.txt", "r")
data = file.read()
print("Saved data:", data)
file.close()
Mini summary: Save game data to a file and load it to restore the game state.
📘 Lesson 15: Putting It All Together – A Simple Phonebook
Definition: A phonebook program uses classes and file I/O to store contacts.
Why is it important? It’s a practical example of how classes and files work together.
Simple explanation: You can add contacts, save them to a file, and load them back.
Real‑life example: Your phone’s contact list.
School example: A school directory of students and parents.
Home example: Your family’s contact list.
Nigerian example: A business contact management system.
Illustration:
class Contact:
def __init__(self, name, phone):
self.name = name
self.phone = phone
def display(self):
print(self.name + ": " + self.phone)
# Save contacts to file...
# Load contacts from file...
Mini summary: Classes and files together can build useful real‑world applications.
📚 Key Vocabulary
| Word | Simple Definition |
|---|---|
| Object | A real‑world thing in code with properties and actions. |
| Class | A blueprint for creating objects. |
| Attribute | A property of an object (like a name). |
| Method | An action that an object can perform. |
| __init__ | The constructor – runs when an object is created. |
| Inheritance | A child class inheriting from a parent class. |
| File | A place on the computer to store data permanently. |
| Read | Getting data from a file. |
| Write | Saving data to a file. |
| Append | Adding data to the end of a file. |
class ClassName: to define the class.__init__ to set up attributes.open("filename", "w")..write()..close().open("filename", "r")..read() or .readlines()..close().This module introduces the concept of Object‑Oriented Programming (OOP). Use physical analogies (like cookie cutters) to explain classes and objects. For file handling, demonstrate with simple text files. Encourage students to create their own classes – like a “Student” or “Car” class.
Encourage your child to identify objects in their daily life – every object has properties and actions. Discuss how a “Toy” could be a class, and their specific toys are objects. This helps reinforce the concept of classes and objects.
pickle?self parameter – all methods need self as the first parameter.__init__ correctly – forgetting to set attributes."w" when you meant "a".Player).self to refer to the current object.with open() – it automatically closes the file for you!
+-------------------+
| Class: Car |
+-------------------+
| Attributes: |
| - make |
| - model |
| - speed |
+-------------------+
| Methods: |
| - accelerate() |
| - brake() |
+-------------------+
| |
v v
+--------+ +--------+
| Car 1 | | Car 2 |
| Toyota | | Honda |
| Camry | | Civic |
| 0 km/h | | 0 km/h |
+--------+ +--------+
| Mode | Description |
|---|---|
| "r" | Read – opens a file for reading (file must exist). |
| "w" | Write – opens a file for writing (overwrites if exists). |
| "a" | Append – opens a file for adding data to the end. |
| "r+" | Read and write – can both read and write. |
Start
|
v
Open file
|
v
Read data
|
v
Process data
|
v
Close file
|
v
End
You have completed Module 5 – a massive achievement! You now understand classes and objects – the building blocks of modern programming. You can define your own classes, create objects, and use inheritance to reuse code. You also learned how to save and load data using files, so your programs can remember things between runs.
These skills are used by professional software engineers every day. You can now build programs that model real‑world things and store data permanently. The world of software engineering is now wide open to you!
You are becoming a true software engineer – keep shining!
__init__? It’s a special method that sets up the object when it’s created.self? It refers to the current object. It’s how you access attributes and methods inside the class."r" mean in file opening? It means read – you open the file to read data."w" mean? Write – you open the file to save data (overwriting any existing data)."a" mean? Append – you add data to the end of the file.pickle – but we learn the basics with text files first.__init__ method used for?self?"w" and "a" in file opening?__init__ is a method that runs when an object is created. (True)"r" is used to write to a file. (False)"w" appends data to a file. (False)__init__ do?self used for?class Car()def Car()class Car:object Car()thisselfmeobj| Term | Definition |
|---|---|
| 1. Class | A. An instance of a class |
| 2. Object | B. A blueprint for objects |
| 3. Attribute | C. An action of an object |
| 4. Method | D. A property of an object |
| 5. Inheritance | E. A child class getting features from a parent |
Answers: 1‑B, 2‑A, 3‑D, 4‑C, 5‑E
__init__ method?Scenario 1: You are building a library management system. Create a Book class with attributes title, author, and year. Add a method display() that prints the book’s details. Create two book objects and display them.
Scenario 2: You want to save your library data. Write code to save the book details to a file, and then read them back.
In groups, design a Student class with attributes for name, age, and grade. Create a method that displays the student’s info. Then, write a program that saves a list of students to a file and loads it back. Present your code to the class.
Write a Python program that defines a Pet class with attributes name, species, and age. Include a method describe(). Create three pet objects and store them in a list. Then, save the list to a file and load it back.
Build a Contact Management System: Create a Contact class with attributes name, phone, and email. Implement functions to add, view, and save contacts to a file. Load contacts from the file when the program starts.
Write a Python program that defines a Product class with attributes name, price, and quantity. Include a method to calculate the total value (price * quantity). Create a list of products, and save the list to a file. Then, read the file and display the total value of all products.
Create a BankAccount class with attributes account_number, owner, and balance. Add methods for deposit(), withdraw(), and display(). Save all accounts to a file, and load them when the program starts. Include error handling for insufficient funds.
Fill‑in‑the‑Blank: 1. class, 2. object, 3. __init__, 4. self, 5. Inheritance, 6. "r", 7. "w", 8. "a", 9. close, 10. properties/data.
True/False: 1F, 2T, 3T, 4T, 5F, 6F, 7T, 8T, 9F, 10F.
Multiple Choice: 1B, 2B, 3B, 4B, 5B, 6B, 7A, 8C, 9A, 10B, 11B, 12B, 13C, 14B, 15D.
In Module 6, you will learn about dictionaries, tuples, and error handling. These are advanced data structures and techniques that make your code more robust and powerful. To prepare, think about how you could store key‑value pairs (like a phonebook where the name is the key and the number is the value).
You have come so far – keep learning and building! See you in Module 6!