Encapsulation & Properties
Encapsulation
Keep an object's data safe and consistent by controlling how it changes. Python relies on naming conventions rather than strict privacy:
| Name | Meaning |
|---|---|
balance | public |
_balance | "internal, please don't touch" (convention) |
__balance | name-mangled to _Account__balance, harder to reach by accident |
@property: getters and setters that look like attributes
@property
def balance(self): ... # read: acc.balance
@balance.setter
def balance(self, value): ... # write: acc.balance = 150
This lets you add validation later without changing the code that uses the class.
Read-only and computed properties
Define only the getter to make a value read-only, or compute it from other attributes (area from width × height).
💡 Prefer methods with clear names for actions (deposit(), withdraw()) and properties for values.
▶️ Runs in the app.
Example
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance can't be negative")
self._balance = value
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
acc = Account("Ana", 100)
acc.deposit(50)
print(acc.balance) # 150
try:
acc.balance = -10
except ValueError as e:
print("Error:", e) # Error: Balance can't be negative