01 / 20

Encapsulation
in Python

Learn how to protect data inside classes, expose only what's needed through methods, and keep your objects consistent and reliable.

Python Programming

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

Data Safety
Prevents external code from putting objects into an invalid or inconsistent state.
Simpler Interface
Hides complex internals so users of the class only see what they need.
Easier Maintenance
Internal changes don't break external code if the public interface stays the same.

Inside the Capsule

class BankAccount Private Data __balance __pin __owner Locked Public Methods deposit() withdraw() get_balance() get_owner() ✕ ✓

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

1. Store Private attributes self.__data 2. Validate Check in methods
\( \text{if amount} > 0 \)
3. Expose Public interface get_data()

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

1
Identify the data your class needs to store (e.g., balance, name, temperature).
2
Make attributes private by prefixing with double underscores: self.__balance.
3
Write getter methods to let outsiders read data: def get_balance(self).
4
Write setter methods with validation: check that values are legal before changing the attribute.
5
Test the boundary: try to break it from outside. If you can, tighten the interface.

Example 1: BankAccount

class BankAccount: def __init__(self, owner, balance=0): self.__owner = owner self.__balance = max(0, balance) def deposit(self, amount): if amount > 0: self.__balance += amount def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount def get_balance(self): return self.__balance

Using BankAccount

acct = BankAccount("Alice", 100) acct.deposit(50) print(acct.get_balance()) # 150 acct.withdraw(200) # Rejected: 200 > 150 print(acct.get_balance()) # Still 150 acct.__balance = -999 # Creates a NEW public attr, # does NOT change the private one print(acct.get_balance()) # Still 150!

Example 2: Temperature Sensor

class TemperatureSensor: def __init__(self): self.__celsius = 0.0 def set_celsius(self, value): if value < -273.15: raise ValueError("Below absolute zero!") self.__celsius = value def get_celsius(self): return self.__celsius def get_fahrenheit(self): return self.__celsius * 9/5 + 32

Example 3: Game Player with HP

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) def is_alive(self): return self.__hp > 0 def get_status(self): return f"{self.__name}: {self.__hp}/{self.__max_hp} HP"

Getters vs @property

Manual Getters/Setters
Explicit method calls: obj.get_x() and obj.set_x(val). Clear intent, works in any OOP language.
@property Decorator
Pythonic approach: access looks like obj.x, but a method runs behind the scenes with full validation.
class Circle: def __init__(self, radius): self.radius = radius # calls the setter @property def radius(self): return self.__radius @radius.setter def radius(self, value): if value <= 0: raise ValueError("Radius must be positive") self.__radius = value

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

✕ No Validation
Writing a setter that blindly assigns the value without checking it: self.__x = value with no guard.
✕ Public Everything
Leaving all attributes public (no underscores) and hoping nobody changes them directly.
✕ Returning Mutable Refs
A getter returns a list reference: external code can .append() and mutate the internal state.

Question 1 of 5

What does the double underscore prefix (__) do to an attribute in Python?

Question 2 of 5

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

p = Player("Hero", 80). After p.take_damage(50) then p.heal(60), what is the HP?