On this page

Encapsulation

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Understanding Encapsulation​

Encapsulation is the object‑oriented principle that bundles data (attributes) and behavior (methods) together while controlling how that data is accessed and modified.

Its purpose is to:

Encapsulation ensures that an object manages its own data responsibly.

Public and Non‑Public Attributes​

Python does not enforce strict access control like some languages, but it uses naming conventions to signal intent.

Public Attributes​

Public attributes are intended for external access.


class Person:

    def __init__(self, name):

        self.name = name      # public

Public attributes form part of the class’s external interface.

Non‑Public Attributes (Single Underscore)​

A leading underscore indicates that an attribute is internal and should not be accessed directly from outside the class.


class Person:

    def __init__(self, name, age):

        self.name = name

        self._age = age       # non‑public

This is a convention, not a restriction. It communicates:

“This is internal. Use methods to interact with it.”

Name‑Mangling for Stronger Protection (Double Underscore)​

A double underscore triggers name‑mangling, making accidental access harder.


class BankAccount:

    def __init__(self, balance):

        self.__balance = balance

Internally, Python renames it to _BankAccount__balance.

This discourages external access and protects critical data.

Using Methods to Control Access​

Encapsulation encourages interacting with object state through methods, not direct attribute access.

Example:


class BankAccount:

    def __init__(self, balance=0):

        self.__balance = balance



    def deposit(self, amount):

        if amount > 0:

            self.__balance += amount

        return self.__balance



    def withdraw(self, amount):

        if 0 < amount <= self.__balance:

            self.__balance -= amount

            return self.__balance

        return "Insufficient funds"

The class controls:

This prevents inconsistent or invalid states.

Getters and Setters (Pythonic Approach)​

In Python, getters and setters are implemented using properties, which provide controlled access while keeping attribute syntax clean.


class Person:

    def __init__(self, name):

        self._name = name



    @property

    def name(self):

        return self._name



    @name.setter

    def name(self, value):

        if value:

            self._name = value

Usage:


p = Person("Alice")

p.name = "Bob"     # setter called

p.name             # getter called

Properties allow:

All while preserving simple attribute access.

Encapsulation and Class Design​

Encapsulation supports clean, maintainable design by:

Well‑encapsulated classes are easier to understand, test, and extend.

Encapsulation vs. Information Hiding​

Python’s philosophy emphasizes responsibility over restriction:

This flexibility makes Python expressive while still supporting strong OOP design.

Summary​

In this lesson, you learned how encapsulation protects and organizes object state. You explored public and non‑public attributes, name‑mangling, controlled access through methods, and Pythonic properties. Encapsulation is essential for designing robust, maintainable classes that expose clear interfaces while safeguarding their internal behavior.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Polymorphism

Next

Magic Methods