Encapsulation
Encapsulation is keeping an object's data and the rules that change it in one place, and exposing a small public surface. Python does this by convention and properties, not by a compiler-enforced private.
Detailed Explanation
A class that lets every caller write order._balance = -5 has no invariant. Encapsulation is the decision that balance changes only through debit and credit, so those methods can refuse a negative result.
Python will not stop a determined caller. There is no private keyword that the interpreter honours. A single leading underscore (_stock) means "this is internal; do not use it outside the class or module". A double leading underscore (__stock) triggers name mangling: the compiler rewrites it to _Order__stock so a subclass does not accidentally overwrite it. Mangling is not encryption. order._Order__stock still works.
The public surface is the names without a leading underscore, plus the documented dunders. Everything else is an implementation detail you can rename. Libraries that reach into _ attributes accept breakage on the next release.
Properties let you keep attribute syntax while running code. @property on balance plus a setter is how you validate on assignment without making callers switch to set_balance. Use a property when the field is conceptually data. Use a method when the operation is a verb or is expensive.
Encapsulation is also about what you pass out. Returning self._items hands the caller the live list. They can .clear() it. Return a tuple, a copy, or an iterator if the collection is yours. The same rule applies to dicts and to objects you did not expect to be mutable.
Modules encapsulate too. __all__ and leading underscores on functions are the module-level version of the same convention. from module import * skips underscored names.
Do not wrap every field in getters and setters because a Java tutorial did. Start with public attributes. Add a property when you need a rule. Add a method when the change is an action.
Code Examples
class Account:
def __init__(self, cents: int):
self._cents = cents
@property
def cents(self) -> int:
return self._cents
def debit(self, amount: int) -> None:
if amount > self._cents:
raise ValueError("insufficient funds")
self._cents -= amount
acct = Account(1000)
acct.debit(250)
print(acct.cents) # 750
# acct.cents = 0 # AttributeError if no setterclass Order:
def __init__(self, sku: str):
self.__sku = sku # mangled to _Order__sku
line = Order("A-1")
print(line._Order__sku) # A-1, still reachable
print([name for name in vars(line)])class Cart:
def __init__(self) -> None:
self._items: list[str] = []
def add(self, sku: str) -> None:
self._items.append(sku)
def items(self) -> tuple[str, ...]:
return tuple(self._items) # a snapshot, not the live listCommon Gotchas
Returning a live internal list
the caller mutates your invariant. Return a copy or a tuple.
Name mangling is not privacy
it avoids subclass clashes. It does not hide data from `vars` or determined access.
A leading underscore is a promise to callers
if you document `_parse` as public, it is public. The convention only works if you keep it.
Properties should be cheap
a `@property` that hits the network looks like a field and surprises everyone. Use a method.