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:
class Account:def __init__(self, balance):self._balance = balance # internal statedef deposit(self, amount):if amount <= 0:raise ValueError("amount must be positive") # protect the invariantself._balance += amountacc = 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:
class Account:def __init__(self, balance):self._balance = balance@propertydef balance(self): # accessed as acc.balance, not acc.balance()return self._balanceacc = 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
- 01Encapsulation hides internal state behind a controlled interface.
- 02A leading underscore marks an attribute as internal (convention, not enforced).
- 03Route changes through methods that validate and protect invariants.
- 04@property exposes a method as an attribute — great for computed/read-only values.
- 05Properties let you add logic later without changing how callers access obj.x.
