Skip to main content
Albero Academy

Encapsulation

Protect internal state and expose a clean interface with properties.

Object-Oriented Programming9 min

Encapsulation means keeping an object's internal state private and exposing a controlled interface to change it. Instead of letting outside code poke at attributes directly, you route changes through methods that can validate and protect invariants.

The underscore convention

Python doesn't enforce private attributes, but a leading underscore (_balance) is the universal signal for "internal — don't touch from outside". A double underscore (__x) triggers name-mangling for stronger (still not absolute) hiding:

a protected interface
class Account:
def __init__(self, balance):
self._balance = balance # internal state
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive") # protect the invariant
self._balance += amount
acc = Account(100)
acc.deposit(50) # goes through validation
# acc.deposit(-99) # ValueError — can't corrupt the balance

Properties

@property exposes a method as if it were an attribute — perfect for computed or read-only values with no ugly getter syntax:

@property
class Account:
def __init__(self, balance):
self._balance = balance
@property
def balance(self): # accessed as acc.balance, not acc.balance()
return self._balance
acc = Account(100)
acc.balance # 100 — reads like an attribute, but it's a method
# acc.balance = 5 # AttributeError — read-only (no setter defined)

Key takeaways

  1. 01Encapsulation hides internal state behind a controlled interface.
  2. 02A leading underscore marks an attribute as internal (convention, not enforced).
  3. 03Route changes through methods that validate and protect invariants.
  4. 04@property exposes a method as an attribute — great for computed/read-only values.
  5. 05Properties let you add logic later without changing how callers access obj.x.

Finished this chapter?

Mark it complete to track your progress through Python.