Encapsulation
in Python
Learn how to protect data inside classes, expose only what's needed through methods, and keep your objects consistent and reliable.
What Is Encapsulation?
Encapsulation is the practice of bundling data (attributes) and the methods that operate on that data into a single unit: a class. It also means restricting direct access to some of an object's internal state so that it can only be changed through well-defined methods.
Why Encapsulation Matters
Inside the Capsule
Python's Naming Conventions
| Convention | Syntax | Meaning |
|---|---|---|
| Public | name | Accessible from anywhere |
| Protected | _name | "Please don't touch" (convention only) |
| Private | __name | Name-mangled: hard to access from outside |
The Core Rule of Encapsulation
This three-step pattern ensures that no attribute can be set to an invalid value, because the method acts as a gatekeeper.
Encapsulation vs Abstraction
| Aspect | Encapsulation | Abstraction |
|---|---|---|
| Focus | How data is protected | What is shown to the user |
| Mechanism | Private attributes + methods | Hiding implementation details |
| Goal | Keep data consistent | Reduce complexity |
| Analogy | A locked safe | A TV remote (hides circuitry) |
How to Apply Encapsulation
Example 1: BankAccount
Using BankAccount
Example 2: Temperature Sensor
Example 3: Game Player with HP
Getters vs @property
When to Use Each Approach
| Scenario | get_x() / set_x() | @property |
|---|---|---|
| Beginner code | ✓ Very explicit | Can be confusing at first |
| Pythonic style | Feels verbose | ✓ Idiomatic |
| Read-only attribute | get_x() only | ✓ @property without setter |
| Cross-language skills | ✓ Works in Java, C++ | Python-only feature |
Common Mistakes
Question 1 of 5
What does the double underscore prefix (__) do to an attribute in Python?
Question 2 of 5
class Wallet:
def __init__(self, cash=0):
self.__cash = max(0, cash)
def spend(self, amount):
if 0 < amount <= self.__cash:
self.__cash -= amount
return True
return False
def get_cash(self):
return self.__cash
What happens when you run: w = Wallet(50); w.__cash = 1000; print(w.get_cash())?
Question 3 of 5
Which of the following best describes the primary goal of encapsulation?
Question 4 of 5
A getter method returns self.__items (a list) directly. Why is this a problem?
Question 5 of 5
class Player:
def __init__(self, name, max_hp=100):
self.__name = name
self.__max_hp = max_hp
self.__hp = max_hp
def take_damage(self, dmg):
if dmg > 0:
self.__hp = max(0, self.__hp - dmg)
def heal(self, amount):
if amount > 0:
self.__hp = min(self.__max_hp, self.__hp + amount)
p = Player("Hero", 80). After p.take_damage(50) then p.heal(60), what is the HP?