Introduction
So far, you have accessed object data directly using attributes such as:
student.name player.health
While this works, it is often not good design.
Encapsulation is an object-oriented principle that:
- Protects data inside an object
- Controls how data can be accessed or changed
- Makes programs safer and easier to maintain
In this lesson, you will learn:
- Why direct access to attributes can be a problem
- How to make attributes “private”
- How to use getter and setter methods
Why Encapsulation Matters
Imagine a bank account where anyone can do this:
account.balance = -1000
This should never be allowed.
Encapsulation solves this by:
- Hiding the data
- Forcing all changes to go through methods
Private Attributes in Python
Python does not have true private variables, but by convention we use a double underscore:
self.__balance
This tells other programmers:
- “Do not access this directly”
- “Use methods instead”
Example: Bank Account with Encapsulation
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
Notice:
- The balance cannot be accessed directly
- All changes go through methods
Predict:
What do you think will happen when this code is run?
class BankAccount:
def __init__(self, balance):
self.__balance = balance
account = BankAccount(100)
print(account.__balance)
Think about:
- Is
__balanceaccessible outside the class? - What error might Python raise?
Run:
Run the program below to check your prediction.
Investigate:
Now let’s access the balance the correct way.
Try this:
- Add a method called
get_balance() - Return the value of
__balance - Use the method to print the balance
Think about:
- Why is this safer than direct access?
- What could we add later without changing the rest of the program?
Modify:
The following program tries to protect the balance, but it contains mistakes.
Fix the code so:
- The balance is private
- Deposits work correctly
- The balance can be read safely
The problem
- The attribute is not private
- The balance is not updated
selfis missing