Python Abstraction and Encapsulation

Learn Python Abstraction and Encapsulation with practical examples, explanations, best practices, and real-world coding techniques.

Abstraction and encapsulation in Python are two important object-oriented programming concepts that help developers manage complexity and protect object state. Although they are often discussed together, they solve different problems.

Abstraction focuses on exposing the important behavior of an object while hiding implementation details. Encapsulation focuses on keeping data and the operations that work with that data together while controlling how the internal state is accessed or changed.

Python takes a flexible approach to both concepts. It does not enforce private fields in the same way as some languages, but it provides conventions such as leading underscores, name mangling, properties, abstract base classes, and protocols that allow developers to design clear interfaces and controlled object state.

What You Will Learn

  • The difference between abstraction and encapsulation
  • How abstraction hides implementation details
  • How abstract base classes define required behavior
  • How encapsulation organizes and protects object state
  • How _single underscore and __double underscore naming work
  • How properties provide controlled attribute access
  • How abstraction and encapsulation work together in real applications
  • Common mistakes and practical design guidelines

Abstraction vs Encapsulation

The two concepts are related, but they are not interchangeable. Abstraction answers the question: "What should the caller need to know?" Encapsulation answers: "How should the object's internal state be managed?"

Concept Main Goal Python Examples
Abstraction Hide unnecessary implementation details. Abstract classes, interfaces, protocols.
Encapsulation Keep state and behavior together and control access. Properties, naming conventions, name mangling.

What Is Abstraction?

Abstraction means exposing only the important interface of an object while hiding how that behavior is implemented internally.

A familiar real-world example is a car. A driver uses operations such as starting, accelerating, braking, and steering without needing to understand every internal engine operation. The interface is simple even though the implementation behind it can be complex.

In Python, the same principle can be applied to application code. A service can expose a method such as send() while hiding connection handling, authentication, formatting, retries, or other internal details.

Simple Abstraction Example

class EmailService:
    def send_email(self, recipient: str, message: str) -> None:
        self._connect()
        self._authenticate()
        self._send_message(recipient, message)
        self._disconnect()

    def _connect(self):
        print("Connecting...")

    def _authenticate(self):
        print("Authenticating...")

    def _send_message(self, recipient: str, message: str):
        print(f"Sending to {recipient}: {message}")

    def _disconnect(self):
        print("Disconnecting...")


service = EmailService()

service.send_email(
    "alex@example.com",
    "Welcome to the platform"
)

The caller only needs to use send_email(). The internal connection and authentication details do not need to be exposed as part of the public interface.

Abstract Base Classes

Python's abc module provides abstract base classes, which are useful when an application needs an explicit interface that concrete classes must implement.

An abstract method describes required behavior. A concrete subclass must provide an implementation before it can be instantiated.

from abc import ABC, abstractmethod


class PaymentProcessor(ABC):

    @abstractmethod
    def pay(self, amount: float) -> None:
        pass


class CardPayment(PaymentProcessor):
    def pay(self, amount: float) -> None:
        print(f"Processing card payment: {amount}")


class UpiPayment(PaymentProcessor):
    def pay(self, amount: float) -> None:
        print(f"Processing UPI payment: {amount}")


card = CardPayment()
upi = UpiPayment()

card.pay(1000)
upi.pay(1000)

The abstract class defines what payment processors must be able to do without deciding exactly how every payment mechanism performs the operation.

Why Use Abstract Classes?

Abstract classes are useful when several implementations belong to the same conceptual family and should follow a clearly defined contract.

  • Define a common interface for related classes.
  • Make required operations visible to developers.
  • Prevent incomplete concrete implementations from being instantiated.
  • Provide a shared base type for related implementations.

What Is Encapsulation?

Encapsulation means combining an object's data and the behavior that operates on that data inside the object while limiting uncontrolled access to its internal state.

Consider a bank account. A balance should not normally be changed arbitrarily by unrelated code. Instead, operations such as deposit and withdrawal can validate changes before modifying the internal state.

class BankAccount:
    def __init__(self, balance: float):
        self._balance = balance

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Deposit must be positive")

        self._balance += amount

    def withdraw(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Withdrawal must be positive")

        if amount > self._balance:
            raise ValueError("Insufficient balance")

        self._balance -= amount

    def get_balance(self) -> float:
        return self._balance


account = BankAccount(500)

account.deposit(200)
account.withdraw(100)

print(account.get_balance())

The class owns the rules for changing the balance. That keeps related state and behavior together and prevents callers from needing to understand every internal detail.

Python Does Not Enforce Traditional Private Fields

Python's approach to encapsulation is based heavily on conventions. A leading underscore communicates that an attribute is intended for internal use, but it is not a strict access modifier enforced by the language.

class User:
    def __init__(self, username: str):
        self.username = username
        self._session_token = "internal-value"


user = User("alex")

print(user.username)
print(user._session_token)

The underscore is a communication mechanism between developers: it says that _session_token is an internal implementation detail and should not normally be accessed directly by outside code.

Double Underscore and Name Mangling

A name beginning with two underscores triggers name mangling. Python changes the attribute name internally to reduce accidental name collisions, especially in inheritance hierarchies.

class Account:
    def __init__(self):
        self.__pin = "1234"

    def verify_pin(self, pin: str) -> bool:
        return pin == self.__pin


account = Account()

print(account.verify_pin("1234"))

A double underscore does not make an attribute absolutely inaccessible. It changes the attribute's internal name using the class name, making accidental access or overriding less likely.

Single Underscore vs Double Underscore

Syntax Meaning Typical Purpose
name Normal public attribute. Public application interface.
_name Internal-use convention. Implementation details.
__name Name-mangled attribute. Reduce accidental collisions in subclasses.

Encapsulation with Properties

Python's @property decorator is one of the most useful tools for encapsulation. It allows code to access a value using normal attribute syntax while the class controls how the value is read or changed.

class Product:
    def __init__(self, price: float):
        self.price = price

    @property
    def price(self) -> float:
        return self._price

    @price.setter
    def price(self, value: float) -> None:
        if value < 0:
            raise ValueError("Price cannot be negative")

        self._price = value


product = Product(100)

print(product.price)

product.price = 150

print(product.price)

The caller uses product.price as if it were a normal field, but the setter ensures that invalid values cannot be assigned through the normal property interface.

Read-Only Properties

A property can provide a getter without providing a setter. This is useful when a value should be exposed for reading but should not be directly assigned by callers.

class User:
    def __init__(self, username: str):
        self.username = username
        self._user_id = 1001

    @property
    def user_id(self) -> int:
        return self._user_id


user = User("alex")

print(user.user_id)

The user_id property provides controlled read access without exposing a normal public setter.

Abstraction Through a Public Interface

A well-designed class often exposes a small public interface while keeping internal helper methods and implementation details separate.

class OrderService:
    def create_order(self, customer_id: int, product_id: int):
        self._validate_customer(customer_id)
        self._validate_product(product_id)
        order = self._build_order(
            customer_id,
            product_id
        )
        self._save_order(order)
        return order

    def _validate_customer(self, customer_id: int):
        print("Validating customer")

    def _validate_product(self, product_id: int):
        print("Validating product")

    def _build_order(self, customer_id: int, product_id: int):
        return {
            "customer_id": customer_id,
            "product_id": product_id
        }

    def _save_order(self, order):
        print("Saving order")


service = OrderService()

order = service.create_order(10, 50)

print(order)

The public operation is create_order(). Internal validation, construction, and persistence details remain inside the service. The caller does not need to know the internal sequence of operations.

Combining Abstraction and Encapsulation

The two concepts become especially powerful when used together. A class can hide its internal state through encapsulation while exposing a simple interface through abstraction.

class ShoppingCart:
    def __init__(self):
        self._items = []

    def add_item(self, name: str, price: float) -> None:
        if price < 0:
            raise ValueError("Price cannot be negative")

        self._items.append({
            "name": name,
            "price": price
        })

    @property
    def total(self) -> float:
        return sum(item["price"] for item in self._items)

    @property
    def item_count(self) -> int:
        return len(self._items)


cart = ShoppingCart()

cart.add_item("Keyboard", 2500)
cart.add_item("Mouse", 1200)

print(cart.total)
print(cart.item_count)

The internal list is not intended to be manipulated directly. Instead, the class exposes meaningful operations such as add_item(), total, and item_count. This gives callers a simpler interface and keeps the object's state under its own control.

Abstraction with Protocols

Python's typing system also provides Protocol, which can describe the behavior expected from an object without requiring inheritance from a specific base class.

from typing import Protocol


class Storage(Protocol):
    def save(self, data: str) -> None:
        ...


class FileStorage:
    def save(self, data: str) -> None:
        print(f"Saving to file: {data}")


class DatabaseStorage:
    def save(self, data: str) -> None:
        print(f"Saving to database: {data}")


def store_data(storage: Storage, data: str) -> None:
    storage.save(data)


store_data(FileStorage(), "Hello")
store_data(DatabaseStorage(), "Hello")

The consuming function only needs to know that the object provides save(). The storage implementation remains an internal concern of the concrete class.

Encapsulation and Validation

One of the most practical benefits of encapsulation is protecting object invariants. An invariant is a condition that should remain true for a valid object.

class Temperature:
    def __init__(self, celsius: float):
        self.celsius = celsius

    @property
    def celsius(self) -> float:
        return self._celsius

    @celsius.setter
    def celsius(self, value: float) -> None:
        if value < -273.15:
            raise ValueError(
                "Temperature cannot be below absolute zero"
            )

        self._celsius = value


temperature = Temperature(25)

temperature.celsius = 30

print(temperature.celsius)

The class controls changes to its state and prevents invalid values from entering through the property setter. This is encapsulation serving a practical business or domain rule.

Abstraction Layers in Application Architecture

Abstraction is not limited to individual classes. It can also appear at the architecture level. For example, application code may depend on a storage interface instead of directly depending on a particular database implementation.

Application Layer

Uses operations such as save() or find() without knowing how storage works internally.

↓

Abstraction

Defines the behavior required by the application.

↓

Implementation

Handles database queries, files, remote APIs, or another storage mechanism.

This separation allows the application to change implementation details without forcing every consumer to understand those changes.

Information Hiding

Information hiding is closely related to both abstraction and encapsulation. The goal is to prevent consumers from becoming unnecessarily dependent on implementation details that may change later.

For example, a service may internally change from one database implementation to another while keeping the public method get_user() unchanged. Callers depend on the abstraction rather than the internal implementation.

Common Mistakes

Thinking __ Means Truly Private

Double underscores trigger name mangling. They do not create an absolute security boundary around data.

Adding Getters and Setters Everywhere

Python does not require Java-style getter and setter methods for every attribute. Properties are often cleaner when controlled access is needed.

Overusing Abstract Classes

Not every small group of classes needs an abstract hierarchy. Add explicit abstraction when it provides a useful contract.

Hiding Everything

Encapsulation is not about making every field inaccessible. It is about designing sensible boundaries around important state and behavior.

Best Practices

  • Expose a small, meaningful public interface for important behavior.
  • Keep implementation details internal when callers do not need to know about them.
  • Use leading underscores to communicate internal attributes and methods.
  • Use name mangling only when avoiding accidental subclass collisions is useful.
  • Use properties when attribute access requires validation or controlled behavior.
  • Use abstract base classes when a shared contract is important.
  • Use protocols when structural typing provides a better fit for the design.
  • Keep validation close to the state it protects.
  • Do not add abstraction merely to make a design look more sophisticated.
  • Prefer simple interfaces that hide complexity without hiding useful behavior.

Practical Example: Payment Service

The following example combines abstraction and encapsulation. The payment service exposes a simple process() operation, while individual payment implementations keep their own internal state and behavior.

from abc import ABC, abstractmethod


class PaymentMethod(ABC):

    @abstractmethod
    def process(self, amount: float) -> str:
        pass


class CardPayment(PaymentMethod):
    def __init__(self, card_number: str):
        self._card_number = card_number

    def process(self, amount: float) -> str:
        masked = "****" + self._card_number[-4:]

        return (
            f"Charged {amount:.2f} using card {masked}"
        )


class UpiPayment(PaymentMethod):
    def __init__(self, upi_id: str):
        self._upi_id = upi_id

    def process(self, amount: float) -> str:
        return (
            f"Charged {amount:.2f} using UPI "
            f"{self._upi_id}"
        )


def checkout(
    payment_method: PaymentMethod,
    amount: float
) -> str:
    if amount <= 0:
        raise ValueError("Amount must be positive")

    return payment_method.process(amount)


payment = CardPayment("1234567890123456")

print(checkout(payment, 2500))

The abstract class defines the expected payment behavior. Each implementation encapsulates its own internal information and processing details. The checkout() function only depends on the abstraction.

Interview Questions to Prepare

  • What is abstraction in Python?
  • What is encapsulation in Python?
  • What is the difference between abstraction and encapsulation?
  • How do abstract base classes work in Python?
  • What is the purpose of the abc module?
  • Does Python have private variables?
  • What is the difference between _name and __name?
  • What is name mangling?
  • How does the @property decorator help encapsulation?
  • When should you use an abstract class versus a protocol?

Summary

Abstraction and encapsulation help Python developers control complexity and create clearer object-oriented designs. Abstraction hides unnecessary implementation details and focuses callers on the operations they need. Encapsulation keeps related state and behavior together and provides controlled access to important internal data.

Python provides several tools for implementing these ideas, including abstract base classes, protocols, properties, leading underscores, and name mangling. The best design is not the one that hides the most code. It is the one that exposes a clear interface while protecting important invariants and keeping implementation details free to evolve.

Code Examples

Abstraction with Abstract Base Class

python
from abc import ABC, abstractmethod


class PaymentProcessor(ABC):

    @abstractmethod
    def pay(self, amount: float) -> None:
        pass


class CardPayment(PaymentProcessor):
    def pay(self, amount: float) -> None:
        print(f"Card payment: {amount}")


class UpiPayment(PaymentProcessor):
    def pay(self, amount: float) -> None:
        print(f"UPI payment: {amount}")


processors = [
    CardPayment(),
    UpiPayment()
]

for processor in processors:
    processor.pay(1000)
    

Encapsulation with Property

python
class Product:
    def __init__(self, price: float):
        self.price = price

    @property
    def price(self) -> float:
        return self._price

    @price.setter
    def price(self, value: float) -> None:
        if value < 0:
            raise ValueError("Price cannot be negative")

        self._price = value


product = Product(100)

product.price = 150

print(product.price)
    

Internal State with Underscore

python
class BankAccount:
    def __init__(self, balance: float):
        self._balance = balance

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Amount must be positive")

        self._balance += amount

    def get_balance(self) -> float:
        return self._balance


account = BankAccount(500)

account.deposit(200)

print(account.get_balance())
    

Name Mangling

python
class Account:
    def __init__(self):
        self.__pin = "1234"

    def verify_pin(self, pin: str) -> bool:
        return pin == self.__pin


account = Account()

print(account.verify_pin("1234"))
    

Abstraction with Protocol

python
from typing import Protocol


class Storage(Protocol):
    def save(self, data: str) -> None:
        ...


class FileStorage:
    def save(self, data: str) -> None:
        print(f"Saving to file: {data}")


class DatabaseStorage:
    def save(self, data: str) -> None:
        print(f"Saving to database: {data}")


def store_data(storage: Storage, data: str) -> None:
    storage.save(data)


store_data(FileStorage(), "Hello")
store_data(DatabaseStorage(), "Hello")
    

Pro Tip

Abstraction decides what callers need to know; encapsulation controls how internal state is managed. Keep the public interface small, protect important invariants with properties or methods, and avoid abstraction that does not simplify the design.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.