Encapsulation
Prerequisites: Classes and objects
Encapsulation means keeping an object's internal details private, and only exposing a deliberate, controlled way to interact with it. Python signals "this is internal, don't touch it directly" with a leading underscore, by convention rather than strict enforcement.
class BankAccount:
def __init__(self, balance):
self._balance = balance # "_" signals: internal use only
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
def balance(self):
return self._balance
Code outside the class calls account.deposit(50) rather than directly
changing account._balance = -1000000, so the validation inside
deposit() can't be bypassed.
Common mistakes
- Relying on the underscore as real security — it's only a convention.
Python doesn't stop external code from touching
_balancedirectly; it just signals that doing so isn't supported.