Encapsulation & Abstraction
Overview
Encapsulation keeps attributes private to prevent accidental modifications, while abstraction hides internal details.
Learning Objectives
- Use single and double underscores to mark private variables.
- Define getter and setter properties using @property.
- Expose clean public interfaces while hiding complex code.
Concept Explanation
Python uses single underscores (_attribute) to indicate protected variables that should not be edited directly. Double underscores (__attribute) trigger name mangling, which changes the variable name internally to make direct access harder. Use @property to create safe getters and setters.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
class Device:
def __init__(self, model):
self._model = model # Protected attribute
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
class Employee:
def __init__(self, name, salary):
self.name = name
self._salary = salary
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, value):
if value < 0:
raise ValueError('Salary cannot be negative')
self._salary = value
emp = Employee('Alex', 5000)
emp.salary = 5500
print(emp.salary)
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
class APIClient:
def __init__(self, api_key):
self.__api_key = api_key # Private key (name mangled)
def fetch_data(self):
self._authenticate()
return 'Data loaded'
def _authenticate(self):
# Hidden helper method
print(f'Authenticating client key...')
client = APIClient('secret_key')
print(client.fetch_data())
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Access property → Run getter method → Return hidden variable → Enforce verification on setters
Common Mistakes
Review these common pitfalls when working with this topic:
- Accessing mangled variables directly (e.g. self.__variable raises AttributeError).
- Writing complex calculations inside property getters, which slows down attribute lookups.
- Forgetting to write setter decorators when trying to update property attributes.
- Using double underscores unnecessarily, which makes testing harder.
Best Practices
Enforce these Pythonic best practices in your codebase:
emp.salary = -100 # Direct modification without validation checks
emp.salary = 100 # Enforces validation checks using setter properties
Quick Revision
Use these key summaries for last-minute revision:
- Encapsulation hides internal object states.
- Single underscore marks protected parameters.
- Double underscores rename variables internally.
- @property defines getter properties.
- @property_name.setter defines attribute setters.
- Keep setters simple for performance.
DataPlayArena Technical Editorial Board
Curated & maintained by enterprise data platform engineers with 10+ years in distributed systems.
Runtime Verification Standards: Every code example, query, and architecture diagram in this tutorial is compiled and verified against real runtimes (Apache Spark 3.5, Python 3.11, PostgreSQL, and DuckDB). If you spot any errata or want to suggest improvements, please submit feedback.