Welcome back, programmer! In Module One, you learned what Object Oriented Programming is. In Module Two, you learned how to write classes and create objects in Python. In Module Three, you learned about inheritance and polymorphism. You learned how one class can inherit from another and how different objects can respond to the same action in their own way.
Now imagine you have built a program with many classes. Your objects have data and methods. But what if someone changes the data in a way that breaks the program? What if someone sets a bank account balance to a negative number? What if someone changes the speed of a car to a million kilometres per hour? That would be a problem.
This is where encapsulation comes in. Encapsulation means keeping data safe inside an object. You hide the data and only allow changes through special methods. This protects your data from mistakes.
We will also learn about abstraction. Abstraction means showing only what is important and hiding the complicated details. When you drive a car, you use the steering wheel and pedals. You do not need to know how the engine works. That is abstraction.
By the end of this module, you will be able to protect your data and simplify your code. You will understand two more pillars of OOP. Let’s begin!
After you finish this module, you will be able to:
abc module in Python.Ngozi lived in Enugu. Her mother worked at a bank. One day, Ngozi asked her mother, “Mama, how do you keep people’s money safe? What if someone just walks in and changes the balance in the computer?”
Her mother smiled. “That is a good question,” she said. “The balance is private. No one can change it directly. If you want to deposit money, you must use the deposit method. If you want to withdraw, you must use the withdraw method. The withdraw method checks if you have enough money. If you do not, it says no.”
Ngozi understood. “So the balance is hidden,” she said. “And you can only change it through special methods that check the rules.”
“Exactly!” said her mother. “That is called encapsulation. We protect the data by hiding it. We only allow changes through safe methods.”
Ngozi was curious. “And what about the customer? They do not see all the complicated bank rules. They just use the ATM.”
Her mother nodded. “That is abstraction. We show the customer only what they need. They press buttons. They do not need to know how the bank’s computers work.”
Ngozi decided that day that she would learn about encapsulation and abstraction. And that is exactly what you will do in this module.
Moral of the story: Encapsulation protects data. Abstraction hides complicated details. Both make programs safer and easier to use.
Definition: Encapsulation is the practice of keeping data safe inside an object. You hide the data and only allow changes through special methods.
Why it is important: It protects data from mistakes and misuse. It keeps your program safe.
Simple explanation: Think of a medicine bottle. The medicine is inside. You cannot just take it out. You must open the cap in the right way. That is encapsulation.
Real-life example: A bank account balance is private. You cannot change it directly. You must use deposit or withdraw.
School example: Your test score is private. The teacher enters it. You cannot change it yourself.
Home example: The money in your piggy bank is private. You must break the piggy bank to get it.
Nigerian example: The goods in a market stall are private. The trader brings them out when you want to buy.
Illustration:
+---------------------+ | OBJECT: BankAccount| | Private: balance | | Public: deposit() | | Public: withdraw() | +---------------------+ You cannot change balance directly. You must use deposit() or withdraw().
Mini summary: Encapsulation keeps data safe. You hide the data and use special methods to change it.
Definition: Public attributes can be accessed from anywhere. Private attributes can only be accessed inside the class.
Why it is important: You need to know which data to hide and which to show.
Simple explanation: Public means everyone can see it. Private means only the class can see it.
Real-life example: Your name is public. Your password is private.
School example: Your name is public. Your test score is private.
Home example: The front door of your house is public. Your bedroom is private.
Nigerian example: The signboard of a shop is public. The account book is private.
Illustration:
Public: name Private: balance You can say: my_account.name You cannot say: my_account.balance
Mini summary: Public attributes are open to everyone. Private attributes are hidden. Use private for sensitive data.
Definition: In Python, you create a private attribute by starting its name with two underscores.
Why it is important: This tells other programmers: “Do not touch this directly.”
Simple explanation: You write self.__balance instead of self.balance.
Real-life example: A bank vault is locked. You need special access.
School example: The exam papers are locked in the principal’s office.
Home example: The medicine cabinet is locked. You need a key.
Nigerian example: The chief’s palace has a private room. Visitors cannot enter.
Example code:
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # public
self.__balance = balance # private
def show_balance(self):
print("Balance: " + str(self.__balance))
Illustration:
self.owner = "Ada" # public
self.__balance = 1000 # private
|
V
Only the class can access __balance
Mini summary: In Python, private attributes start with two underscores. They cannot be accessed from outside the class.
Definition: A getter is a method that returns the value of a private attribute. A setter is a method that changes the value safely.
Why it is important: They let you control how data is accessed and changed.
Simple explanation: A getter says “here is the value”. A setter says “I will change the value, but only if it is safe”.
Real-life example: A bank teller can tell you your balance (getter) and can deposit money (setter).
School example: A teacher can tell you your score (getter) and can change it after remarking (setter).
Home example: A parent can tell you the WiFi password (getter) and can change it (setter).
Nigerian example: A trader can tell you the price (getter) and can change it during bargaining (setter).
Example code:
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance
def get_balance(self):
return self.__balance
def set_balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Error: Balance cannot be negative.")
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print("Deposited: " + str(amount))
else:
print("Error: Deposit must be positive.")
def withdraw(self, amount):
if amount > 0 and amount <= self.__balance:
self.__balance -= amount
print("Withdrawn: " + str(amount))
else:
print("Error: Invalid withdrawal.")
Illustration:
get_balance() -> returns balance set_balance() -> changes balance if safe deposit() -> adds money if positive withdraw() -> removes money if enough
Mini summary: Getters return private data. Setters change private data safely. They protect your data.
Definition: Encapsulation matters because it keeps your program safe and organised.
Why it is important: Without encapsulation, anyone can change your data and break your program.
Simple explanation: Imagine a car. You can press the accelerator to go faster. But you cannot directly change the engine speed. The car protects you from making dangerous changes.
Real-life example: A microwave has a door. You cannot run it with the door open. It protects you.
School example: A school has a gate. You cannot just walk in. You must sign in at the office.
Home example: A fridge has a door. You cannot change the temperature by touching the cooling system.
Nigerian example: A bank has a security guard. You cannot just walk into the vault.
Illustration:
Without Encapsulation: balance = -5000 (BAD!) With Encapsulation: withdraw(5000) -> checks balance first
Mini summary: Encapsulation protects data. It stops mistakes and keeps your program safe.
Definition: Abstraction means showing only what is important and hiding the complicated details.
Why it is important: It makes things easier to use. You do not need to know how everything works.
Simple explanation: When you drive a car, you use the steering wheel and pedals. You do not need to know how the engine works. That is abstraction.
Real-life example: When you use a phone, you press buttons. You do not need to know how the screen works.
School example: When you write with a pen, you do not need to know how the ink flows.
Home example: When you use a TV remote, you press buttons. You do not need to know how the signal works.
Nigerian example: When you buy food from a trader, you do not need to know how the food was cooked.
Illustration:
+---------------------+ | CAR | | Steering wheel | | Pedals | | (Engine hidden) | +---------------------+ You use the car without knowing the engine.
Mini summary: Abstraction hides complicated details. It shows only what you need to use.
Definition: An abstract class is a class that cannot be used to create objects directly. It is meant to be inherited from.
Why it is important: It defines a common blueprint for other classes.
Simple explanation: An abstract class says: “All my children must have these methods.” But it does not say how those methods work.
Real-life example: A “Vehicle” abstract class says all vehicles must have a move method. But cars move differently from boats.
School example: A “Person” abstract class says all people must have a study method. But students study differently.
Home example: An “Appliance” abstract class says all appliances must have a work method. But fridges work differently from fans.
Nigerian example: A “Trader” abstract class says all traders must have a sell method. But food traders sell differently from cloth traders.
Illustration:
Abstract Class: Vehicle
|
V
Must have: move()
|
V
+--------+ +--------+ +--------+
| Car | | Boat | | Plane |
| move() | | move() | | move() |
+--------+ +--------+ +--------+
Mini summary: An abstract class is a blueprint that cannot be used directly. It defines what child classes must have.
Definition: In Python, you use the abc module to create abstract classes.
Why it is important: It enforces rules. Child classes must implement abstract methods.
Simple explanation: You import ABC and abstractmethod. You write @abstractmethod above the method.
Real-life example: A school says all students must wear a uniform. The uniform design is abstract.
School example: A teacher says all projects must have a cover page. The cover page is abstract.
Home example: A recipe says all cakes must have flour. The flour is abstract.
Nigerian example: A tailor says all dresses must have sleeves. The sleeves are abstract.
Example code:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def move(self):
pass
class Car(Vehicle):
def move(self):
print("Car is driving.")
class Boat(Vehicle):
def move(self):
print("Boat is sailing.")
# my_vehicle = Vehicle() # ERROR! Cannot create object
my_car = Car()
my_car.move() # Car is driving.
Illustration:
from abc import ABC, abstractmethod
|
V
class Vehicle(ABC):
@abstractmethod
def move(self):
pass
|
V
Child classes MUST implement move()
Mini summary: In Python, abstract classes use ABC and @abstractmethod. Child classes must implement abstract methods.
Definition: Encapsulation protects data. Abstraction hides complexity.
Why it is important: They are different but work together.
Simple explanation: Encapsulation is about safety. Abstraction is about simplicity.
Real-life example: A bank vault is encapsulation (safe). The ATM is abstraction (simple to use).
School example: The principal’s office is encapsulation (private). The school timetable is abstraction (simple to read).
Home example: The medicine cabinet is encapsulation (locked). The TV remote is abstraction (simple buttons).
Nigerian example: The bank vault is encapsulation (safe). The ATM is abstraction (easy to use).
Table: Encapsulation vs Abstraction
| Feature | Encapsulation | Abstraction |
|---|---|---|
| What it does | Protects data | Hides complexity |
| Focus | Safety | Simplicity |
| How | Private attributes, getters, setters | Abstract classes, methods |
| Example | Bank balance | Car steering wheel |
Mini summary: Encapsulation protects data. Abstraction hides complexity. Both make programs better.
Definition: A property is a special way to use getters and setters in Python. It looks like an attribute but uses methods.
Why it is important: It makes your code cleaner and easier to read.
Simple explanation: You use @property for the getter and @name.setter for the setter.
Real-life example: You ask for “balance” and the bank tells you. You say “set balance to 500” and the bank checks first.
School example: You ask for “score” and the teacher tells you. You say “set score to 90” and the teacher checks.
Home example: You ask for “temperature” and the fridge tells you. You say “set temperature to 5” and the fridge checks.
Nigerian example: You ask for “price” and the trader tells you. You say “set price to 200” and the trader checks.
Example code:
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance
@property
def balance(self):
return self.__balance
@balance.setter
def balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Error: Balance cannot be negative.")
account = BankAccount("Ada", 1000)
print(account.balance) # 1000
account.balance = 2000 # OK
account.balance = -500 # Error
Illustration:
@property
def balance(self):
return self.__balance
|
V
account.balance -> calls getter
@balance.setter
def balance(self, amount):
if amount >= 0:
self.__balance = amount
|
V
account.balance = 2000 -> calls setter
Mini summary: Properties make getters and setters look like attributes. They keep your code clean.
Definition: You can use encapsulation and abstraction together in a real program.
Why it is important: It shows how these ideas work in practice.
Simple explanation: You create a Student class with private scores. You add methods to add scores and get the average.
Real-life example: A school management system tracks student scores.
School example: A teacher uses a program to record and calculate scores.
Home example: A parent tracks their child’s progress.
Nigerian example: A school in Lagos uses a program to manage student results.
Example code:
class Student:
def __init__(self, name):
self.name = name
self.__scores = []
def add_score(self, score):
if 0 <= score <= 100:
self.__scores.append(score)
else:
print("Error: Score must be between 0 and 100.")
def get_average(self):
if len(self.__scores) == 0:
return 0
return sum(self.__scores) / len(self.__scores)
def show_scores(self):
print(self.name + "'s scores: " + str(self.__scores))
ada = Student("Ada")
ada.add_score(85)
ada.add_score(90)
ada.add_score(78)
ada.show_scores()
print("Average: " + str(ada.get_average()))
Output:
Ada's scores: [85, 90, 78] Average: 84.33333333333333
Illustration:
Student
|
V
Private: __scores
Public: add_score(), get_average(), show_scores()
Mini summary: You can use encapsulation to protect scores and methods to work with them safely.
Definition: You can use abstraction to define a common blueprint for shapes.
Why it is important: It shows how abstraction works in practice.
Simple explanation: You create an abstract Shape class with an abstract area method. Then Circle, Square, and Triangle implement it.
Real-life example: A drawing program calculates areas of different shapes.
School example: A maths program calculates areas.
Home example: A garden planner calculates areas of plots.
Nigerian example: A land surveyor calculates areas of plots.
Example code:
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
shapes = [Circle(5), Square(4), Triangle(6, 3)]
for shape in shapes:
print("Area: " + str(shape.area()))
Output:
Area: 78.53981633974483 Area: 16 Area: 9.0
Illustration:
Abstract Shape
|
V
+--------+ +--------+ +--------+
| Circle | | Square | |Triangle|
| area() | | area() | | area() |
+--------+ +--------+ +--------+
Mini summary: Abstract classes define a blueprint. Child classes implement the details.
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:
Illustration:
Bad Code Good Code +----------------+ +----------------+ | self.balance | | self.__balance | | (public) | | (private) | +----------------+ +----------------+
Mini summary: Avoid common mistakes. Use private only for sensitive data. Always implement abstract methods.
Definition: These are good habits to follow.
Why it is important: They make your code better.
Simple explanation: Here are some best practices.
List of best practices:
Illustration:
Best Practice: - Private data - Safe setters - Abstract blueprints - Clear names
Mini summary: Follow best practices. Protect data. Simplify complexity. Keep code clean.
Definition: You will now combine encapsulation and abstraction in one program.
Why it is important: This is how real OOP programs work.
Simple explanation: Create an abstract class. Create child classes. Use private data. Use getters and setters. Create objects and use them.
Real-life example: A payment system with different payment methods.
School example: A grading system with different subjects.
Home example: A smart home system with different appliances.
Nigerian example: A market system with different types of traders.
Example code:
from abc import ABC, abstractmethod
class Payment(ABC):
def __init__(self, amount):
self.__amount = amount
@property
def amount(self):
return self.__amount
@amount.setter
def amount(self, value):
if value > 0:
self.__amount = value
else:
print("Error: Amount must be positive.")
@abstractmethod
def pay(self):
pass
class CardPayment(Payment):
def pay(self):
print("Paid " + str(self.amount) + " with card.")
class CashPayment(Payment):
def pay(self):
print("Paid " + str(self.amount) + " with cash.")
payments = [CardPayment(5000), CashPayment(2000)]
for payment in payments:
payment.pay()
Output:
Paid 5000 with card. Paid 2000 with cash.
Illustration:
Abstract Payment
|
V
+-------------+ +-------------+
| CardPayment | | CashPayment |
| pay() | | pay() |
+-------------+ +-------------+
Private: __amount
Public: amount (property), pay()
Mini summary: You can combine encapsulation and abstraction. Abstract classes define blueprints. Private data protects information.
| Word | Simple Definition |
|---|---|
| Encapsulation | Keeping data safe inside an object. |
| Public attribute | Data that anyone can access. |
| Private attribute | Data that only the class can access. |
| Getter | A method that returns private data. |
| Setter | A method that changes private data safely. |
| Property | A special way to use getters and setters in Python. |
| Abstraction | Hiding complicated details. |
| Abstract class | A class that cannot be used directly. It is a blueprint. |
| Abstract method | A method that must be implemented by child classes. |
| ABC | Abstract Base Class. A module in Python. |
| Name mangling | How Python makes attributes private. |
| Validation | Checking that data is correct. |
self.__balance.def get_balance(self): return self.__balance.def set_balance(self, amount): ....ABC and abstractmethod from abc.class MyClass(ABC):.@abstractmethod above methods.abc module was added in Python 2.6.
Create Class
|
V
Add Private Data
|
V
Add Getters/Setters
|
V
Create Abstract Methods
|
V
Create Child Classes
|
V
Implement Methods
|
V
Use Objects Safely! 🎉
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 | Public | Private |
|---|---|---|
| Who can access? | Anyone | Only the class |
| Python syntax | self.name | self.__name |
| Example | Name | Balance |
| Best for | General data | Sensitive data |
| Feature | Encapsulation | Abstraction |
|---|---|---|
| What it does | Protects data | Hides complexity |
| Focus | Safety | Simplicity |
| How | Private attributes, getters, setters | Abstract classes, methods |
| Example | Bank balance | Car steering wheel |
Lesson 1: Encapsulation keeps data safe inside an object.
Lesson 2: Public attributes are open. Private attributes are hidden.
Lesson 3: In Python, private attributes start with two underscores.
Lesson 4: Getters return data. Setters change data safely.
Lesson 5: Encapsulation protects data from mistakes.
Lesson 6: Abstraction hides complicated details.
Lesson 7: Abstract classes are blueprints for other classes.
Lesson 8: In Python, use ABC and @abstractmethod.
Lesson 9: Encapsulation protects data. Abstraction hides complexity.
Lesson 10: Properties make getters and setters look like attributes.
Lesson 11: You can use encapsulation to protect student scores.
Lesson 12: You can use abstraction to define a shape blueprint.
Lesson 13: Avoid common mistakes. Use private only for sensitive data.
Lesson 14: Follow best practices. Protect data. Simplify code.
Lesson 15: You can combine encapsulation and abstraction in one program.
In this module, you learned about encapsulation and abstraction. You learned that encapsulation keeps data safe by hiding it and using getters and setters. You learned that abstraction hides complicated details and shows only what is needed. You learned how to create private attributes in Python. You learned how to use properties. You learned how to create abstract classes and methods using the abc module. You also learned the difference between encapsulation and abstraction and how they work together. You are now ready for Module Five, where you will put everything together in a complete project.
ABC and @abstractmethod.Match the word to its meaning.
| Word | Meaning |
|---|---|
| 1. Encapsulation | A. A method that returns private data |
| 2. Getter | B. Keeping data safe inside an object |
| 3. Setter | C. A class that cannot be used directly |
| 4. Abstraction | D. A method that changes private data safely |
| 5. Abstract class | E. Hiding complicated details |
Answers: 1-B, 2-A, 3-D, 4-E, 5-C
Title: Protect and Simplify
Instructions: In groups of 3, choose a class (e.g., BankAccount, Student, Pet). Add private attributes. Add getters and setters. Add an abstract class. Create child classes. Present to the class.
Title: My First Encapsulation
Instructions: Write a class called BankAccount with private balance. Add deposit, withdraw, and get_balance methods. Test with different amounts. Write down what happens.
Title: A Complete Student Management System
Instructions: Create an abstract class Person with name and age. Create a child class Student with private scores. Add methods to add scores, get average, and show scores. Create multiple students. Test your program. Present to the class.
Task: Write a short paragraph (5 sentences) explaining what you learned about encapsulation and abstraction. Then, list three things you found easy and one thing you found hard. Finally, describe the class you created and how it protects data.
In Module Five, we will learn about putting it all together. You will build a complete OOP program using classes, objects, inheritance, polymorphism, encapsulation, and abstraction. To get ready, make sure you:
See you in Module Five! 🚀
End of Module Four · Object Oriented Programming