Encapsulation
Python · Functions & OOP
Theory
Encapsulation means bundling data and the methods that work on it inside one class, and controlling how outside code reaches that data. Python has no strict private keyword; it uses naming conventions instead. A single underscore, self._balance, signals 'internal, please do not touch' but is still accessible. A double underscore, self.__balance, triggers name mangling: Python renames it to _Account__balance, so a.__balance from outside raises AttributeError.
The usual pattern is to keep the raw data internal and expose safe methods such as get_balance() or deposit(amount) that can validate input (reject negative deposits) before changing state. The @property decorator lets you offer method-backed access with simple attribute syntax, like a.balance.
Why we use it
It protects an object's internal state from accidental or invalid changes, so the object is always in a valid condition. Callers depend on a stable set of methods, so you can change the internals later without breaking them.
When to use it
Use it for data with rules, such as balances that must not go negative or salaries that need validation. For simple data holders with no rules, plain public attributes are fine and very Pythonic.
How it works
- Outside code wants to change the balance
- Via a public method like deposit()? Yes: Validate the amount. No: a.__balance fails (mangled).
- Is the amount valid (> 0)? Yes: Update self.__balance. No: Raise ValueError.
- Object stays in a valid state
Syntax
class C:
def __init__(self):
self._protected = 1
self.__private = 2Example
class Account:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
a = Account(500)
print(a.get_balance())Key points
- A single leading underscore signals 'internal use' by convention only
- A double leading underscore triggers name-mangling for stronger protection
- Name mangling is not true security - _Account__balance is still reachable
- Expose behaviour through methods that validate input
- @property gives attribute-style access backed by a method