Encapsulation
Encapsulation
As programs grow, you do not always want data changed directly.
Sometimes values should be protected and updated in a controlled way.
This idea is called encapsulation.
What Is Encapsulation?
Encapsulation means:
- keeping data and methods together
- controlling access to data
- protecting important values
In simple Python learning, we often use methods to update data instead of changing values directly.
Real Example
A bank account balance should not be changed carelessly.
Bad idea:
account.balance = -5000
Better idea:
Use a method like deposit() or withdraw().
Private Style Attributes
Python uses a naming style with _ or __.
Examples:
_balance__balance
This tells other programmers:
Do not change this directly.
Example: Protected Balance
class BankAccount:
def __init__(self, balance):
self._balance = balance
account = BankAccount(100)
print(account._balance)
Output
100
Better: Use Methods
class BankAccount:
def __init__(self, balance):
self._balance = balance
def deposit(self, amount):
self._balance += amount
def show_balance(self):
print(self._balance)
account = BankAccount(100)
account.deposit(50)
account.show_balance()
Output
150
Add Rules with Methods
class BankAccount:
def __init__(self, balance):
self._balance = balance
def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
else:
print("Not enough money")
def show_balance(self):
print(self._balance)
account = BankAccount(100)
account.withdraw(30)
account.show_balance()
Output
70
Why This Matters
Methods let you:
- validate values
- stop bad changes
- keep code organized
Common Beginner Idea
You do not need advanced privacy rules yet.
Focus on this habit:
Use methods to manage important data.
Code Along
Create a class called Wallet.
Add:
_moneyadd_money()show_money()
Mini Challenge
Create a class called GamePlayer.
Steps:
- Start with
_health = 100 - Create method
take_damage(amount) - Reduce health
- Create method
show_health()
Example:
80
(after damage of 20)
Real World Use Case
Apps use encapsulation for balances, passwords, settings, stock counts, and user data.
Quiz
- What is encapsulation?
- Why use methods instead of direct changes?
- What does
_balancesuggest? - Why is encapsulation useful?
Assignment
Create a StockItem class with _quantity, add_stock(), and show_stock().
Summary
You learned that encapsulation protects data by using methods to control how values are changed.