Python - Encapsulation & Data Hiding
Overview
Estimated time: 15–25 minutes
Encapsulation protects invariants and exposes a clean API. In Python, naming conventions and properties support encapsulation without strict privacy.
Learning Objectives
- Use naming conventions (
_name
,__mangled
) and modules to limit surface area. - Apply
@property
for validation and computed attributes. - Expose a stable API and hide implementation details.
Examples
class Account:
def __init__(self, balance: float):
self._balance = balance # protected by convention
@property
def balance(self) -> float:
return self._balance
@balance.setter
def balance(self, value: float) -> None:
if value < 0:
raise ValueError("negative balance")
self._balance = value
Guidance & Patterns
- Use a leading underscore for non-public members; respect it in consumers.
- Prefer composition over inheritance to narrow exposed surface.
Best Practices
- Document your public API; use
__all__
to controlfrom module import *
. - Keep invariants in setters or dedicated methods; validate early.
Exercises
- Refactor a class to use
@property
with validation instead of direct attribute writes. - Use
__all__
in a package to define the public API.