Learn Python
>>> oop_fundamentals.encapsulation

Encapsulation in Python

#concept

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.

#how it works
1

Signal internal data with a naming convention

Usually a single leading underscore, warning it shouldn’t be touched directly.

2

Provide methods for safe access

Reading or updating that data through methods that apply any needed checks.

3

Callers go through those methods

Rather than reaching in and changing the data directly.

4

Internal representation stays free to change

As long as the public methods keep working the same way from the outside.

5

@property offers a more elegant version

Making controlled access look exactly like plain attribute access.

#example
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())
Output
150
1_balance is stored behind a single underscore, signaling it shouldn’t be modified directly from outside the class.
2deposit(50) goes through the method, which checks that the amount is positive before applying it, increasing the balance to 150.
3deposit(-1000) is rejected silently by the same check, since amount > 0 is False — the balance stays unaffected.
4get_balance() provides the only sanctioned way to read the value, keeping every change to _balance funneled through code that can validate it.
#use cases
Protecting an object's data from being set to an invalid or inconsistent state from outside
Validating input before it is stored, like rejecting a negative deposit or an invalid email format
Hiding internal implementation details so they can change later without breaking code that uses the class
Building the same kind of guardrails real-world systems need, like a bank account that can't go negative through a plain assignment

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.