Skip to main content

Encapsulation in Python

OOP Design

Encapsulation

Encapsulation isn't about private keywords—it's about clear boundaries. Use naming conventions, properties, and helper classes to build trustable APIs.

Naming conventions

  • _single_leading_underscore signals "internal use."
  • __double_leading triggers name mangling—rarely needed.
  • property allows validation while exposing attribute-like syntax.
class Account:
def __init__(self):
self._balance = 0.0

@property
def balance(self) -> float:
return self._balance

def deposit(self, amount: float) -> None:
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount

Composition > inheritance

Encapsulation thrives when responsibilities are split into collaborating objects instead of huge base classes.

Next up in your learning path