Encapsulation in Python
Encapsulation means bundling an object's data together with the methods that operate on it, and controlling access to that data through those methods rather than allowing direct, unchecked outside manipulation. In Python this is achieved through the naming convention covered in Access Modifiers, combined with methods that validate or process a value before it's stored.
Signal internal data with a naming convention
Usually a single leading underscore, warning it shouldn’t be touched directly.
Provide methods for safe access
Reading or updating that data through methods that apply any needed checks.
Callers go through those methods
Rather than reaching in and changing the data directly.
Internal representation stays free to change
As long as the public methods keep working the same way from the outside.
@property offers a more elegant version
Making controlled access look exactly like plain attribute access.
class BankAccount: def __init__(self, balance): self._balance = balance def deposit(self, amount): if amount > 0: self._balance += amount def get_balance(self): return self._balance acc = BankAccount(100)acc.deposit(50)acc.deposit(-1000)print(acc.get_balance())Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.