Demystifying Encapsulation and Information Hiding in Python

Defining the Two Pillars of Design

Many developers use

and
Information Hiding
interchangeably, but they serve distinct roles in software architecture. Encapsulation is the act of grouping related data and behaviors into a single unit, like a Customer class that contains names, IDs, and addresses. It creates a complete representation of an entity. Beyond grouping, it also establishes boundaries. These boundaries restrict how external code interacts with internal data, often using access modifiers like private or protected members.

Information hiding is the strategic concealment of implementation details. It provides a "black box" interface, allowing other modules to interact with a component without knowing its internal mechanics. When you use a

payment processor, your main application shouldn't care about specific
API
calls or data transformations happening under the hood. It only needs to know how to trigger a payment.

Implementation and Access Control

In

, encapsulation is often signaled through naming conventions. While the language doesn't strictly enforce access restrictions like
Java
, developers use single or double underscores to indicate intent.

class Order:
    def __init__(self):
        # Protected member: a boundary for encapsulation
        self._payment_status = "PENDING"

    def pay(self):
        # Information hiding: user doesn't see the internal logic
        self._payment_status = "PAID"

    def is_paid(self) -> bool:
        return self._payment_status == "PAID"

In this Order class, _payment_status is protected. By providing methods like is_paid(), we hide the internal representation. If we later change the status from a string to an integer, external code remains untouched because it relies on the method, not the variable.

Impact on Cohesion and Coupling

These concepts directly influence the health of your codebase. Encapsulation increases cohesion by ensuring that a class does exactly what it's supposed to do and nothing more. Information hiding reduces coupling by removing dependencies between different parts of the system. High cohesion and low coupling make your software easier to maintain, test, and scale over time.

Syntax Notes and Best Practices

Python uses the _ prefix for protected members and __ for private members (which triggers name mangling). Always prefer high-level methods over direct variable access to maintain the integrity of your information hiding strategy. Use

to represent states clearly without exposing raw strings or integers to the end-user.

Demystifying Encapsulation and Information Hiding in Python

Fancy watching it?

Watch the full video and context

2 min read