Encapsulation example
1class BankAccount:
2def __init__(self):
3self.__balance = 0 # Private
4def deposit(self, amt): # Public
5self.__balance += amt
Encapsulation binds data and methods together and restricts direct access using public and private access levels.
Keep _balance inside. deposit/withdraw are the only doors.
Encapsulation wraps data (attributes) and methods (functions) into a single unit called a class, and controls how the outside world accesses them using access modifiers.
classDiagram
class BankAccount {
+deposit(amt)
+withdraw(amt)
-__balance: int
}
BankAccount : +deposit(amt)
BankAccount : +withdraw(amt)
BankAccount : -__balance
A car's engine is encapsulated in metal—you can't access it directly. You control it through the steering wheel, pedals, and buttons (public interface). Private parts prevent damage.