🐍 Lesson 5: Encapsulation
1. What is encapsulation?
In short → Encapsulation is an OOP concept that bundles data (attributes) and methods (functions) together inside a class, protecting them from being accessed directly from outside.
In detail → Encapsulation is the concept of bundling data (attributes) and methods (functions) inside a class, while restricting direct access to some of the object's components.
2. Why Encapsulation?
- Protects data from accidental modification
- Provides controlled access (via getters & setters)
- Improves maintainability and security
- Hides internal implementation details
3. Summary
✅ Encapsulation = hide data, expose only safe methods
✅ Use __private attributes to protect data
✅ Getters & setters provide controlled access
✅ Real-world analogy = ATM interface to bank account
python
# ===== 1. Without Encapsulation (Problem) =====
class BankAccount:
def __init__(self, balance):
self.balance = balance # public
account = BankAccount(1000)
account.balance = -500 # ❌ invalid, but possible
print(f"Balance: {account.balance}") # -500
# ===== 2. With Encapsulation (Solution) =====
class BankAccountProtected:
def __init__(self, balance):
self.__balance = balance # private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
def get_balance(self):
return self.__balance
account2 = BankAccountProtected(1000)
account2.deposit(500)
account2.withdraw(200)
print(f"\nProtected Balance: {account2.get_balance()}") # 1300
# ===== 3. Getters & Setters =====
class Person:
def __init__(self, name):
self.__name = name
def get_name(self): # getter
return self.__name
def set_name(self, new_name): # setter
if len(new_name) > 0:
self.__name = new_name
p = Person("Sai")
print(f"\nName: {p.get_name()}") # Sai
p.set_name("Aye")
print(f"Name: {p.get_name()}") # AyeYou should see
Balance: -500 Protected Balance: 1300 Name: Sai Name: Aye