Sub topic 2
What encapsulation means in Python
This chapter assumes you can define classes and methods, set instance attributes in __init__, read basic decorator syntax, and raise and catch exceptions.
The idea
Encapsulation means a class controls how its data is read and changed. Code outside the class uses a small public interface. The details behind that interface stay inside the class, so you can change them later without breaking callers.
Many languages enforce this with keywords such as private. Python does not. Any code can read or assign any attribute of an object. Python's approach is often summed up as "we are all consenting adults here". The language gives you conventions and tools, and the programmers on the project agree to follow them.
What goes wrong without it
Consider a class that exposes its data as a plain attribute:
class Account:
def __init__(self, balance):
self.balance = balance
acct = Account(100)
acct.balance = -50
print(acct.balance) # -50Nothing stops the invalid balance. If you later need a rule such as "the balance may never be negative", every caller that assigns to balance is a possible bug. Encapsulation puts that rule in one place, inside the class.
Public interface and internal state
Think of two layers. The public interface is the set of names that outside code is meant to use. The internal state is the data and helper methods that exist only to support the interface.
Python offers three tools for this, each covered in later chapters:
| Tool | What it does | Enforced? |
|---|---|---|
| Leading underscore names | Mark an attribute as internal | No, convention only |
| Double underscore names | Rename an attribute to avoid clashes in subclasses | No, the new name is still reachable |
| `@property` | Run code when an attribute is read or assigned | Yes, the code always runs |
Only @property changes behavior. The underscore tools only communicate intent.
Methods as the first tool
The most direct way to protect state is to route changes through methods that check them:
class Account:
def __init__(self, balance):
self._balance = balance
def get_balance(self):
return self._balance
def withdraw(self, amount):
if amount > self._balance:
raise ValueError("insufficient funds")
self._balance -= amount
acct = Account(100)
acct.withdraw(30)
print(acct.get_balance()) # 70
try:
acct.withdraw(500)
except ValueError as exc:
print(exc) # insufficient fundsThis works, but get_balance() is clumsy for simple reads. Code like this is also awkward to change later. If balance started as a plain attribute and callers already write acct.balance, switching to get_balance() breaks them all. Properties solve this. They let you start with a plain attribute and add checks later, and callers keep using the same acct.balance syntax.
What encapsulation does not do
- It does not provide security. Any code in the process can reach any attribute, including ones marked internal.
- It does not mean every attribute needs protection. A plain attribute with no rules needs no wrapper.
- It does not require a particular syntax. A documented public method, a property, and a clear naming convention are all legitimate forms of it.
Exercise
A class has a public attribute price, and many callers already write item.price = 5. You now need to reject negative prices. Why is a property a better fix than replacing the attribute with set_price()?
Show answer
A property keeps the item.price = 5 syntax working, so existing callers do not change, while the class gains a place to run the validation. Replacing the attribute with set_price() would break every caller that assigns to price.