intermediate

Encapsulation & Abstraction

7 min readLast updated: 2026-07-12

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.

python
class Device:
    def __init__(self, model):
        self._model = model # Protected attribute

Example 2 — Everyday Usage

This example demonstrates a realistic scenario handling business parameters.

python
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.

python
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:

text
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:

❌ Don't
python
emp.salary = -100 # Direct modification without validation checks
✅ Do
python
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.