What is Encapsulation?
Encapsulation is an Object-Oriented Programming (OOP) concept where data (attributes) and methods (functions) are bundled together in a class and access to the data is controlled to protect it from unintended interference or misuse.
Why Encapsulation?
- Data hiding (restricting direct access to variables)
- Better maintainability
- Controlled access through getter and setter methods
Access Modifiers in Python
Python does not have strict access modifiers like some other languages, but it uses naming conventions:
| Modifier | Syntax Example | Meaning |
|---|---|---|
| Public | self.name | Accessible from anywhere |
| Protected | self._name | Convention: should not be accessed outside the class (still possible) |
| Private | self.__name | Name mangling makes it harder to access from outside |
For Example:
class BankAccount: def __init__(self, account_holder, balance): self.account_holder = account_holder # Public attribute self._account_type = "Savings" # Protected attribute self.__balance = balance # Private attribute # Getter for balance def get_balance(self): return self.__balance # Setter for balance with validation def deposit(self, amount): if amount > 0: self.__balance += amount print(f"Deposited ₹{amount}. New balance: ₹{self.__balance}") else: print("Deposit amount must be positive.") def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount print(f"Withdrew ₹{amount}. Remaining balance: ₹{self.__balance}") else: print("Invalid withdrawal amount.")# Usageaccount = BankAccount("Rahul", 5000)# Public accessprint(account.account_holder) # ✅ Works# Protected access (possible but discouraged)print(account._account_type) # ⚠️ Works but not recommended# Private access (will cause error)# print(account.__balance) # ❌ AttributeError# Correct way to access private dataprint("Balance:", account.get_balance())# Modify balance safelyaccount.deposit(2000)account.withdraw(1000)
Key Points
- Public: Accessible anywhere.
- Protected: Accessible but should be treated as internal.
- Private: Not directly accessible; use getters/setters.
- Name Mangling: Private attributes are internally renamed to
_ClassName__attributeto avoid accidental access.
