Tutorials Python Python Encapsulation
Ch 34 / 58
Python Intermediate 12 min read Chapter 34 of 58

Python Encapsulation

Encapsulation is the OOP principle of bundling data (attributes) and the methods that operate on that data inside a single class, and controlling access to that data from the outside world. Instead of letting anyone freely read or modify internal state, you expose a carefully designed interface. This chapter covers Python's three access levels (public, protected, private), name mangling, the elegant @property decorator for getter/setter/deleter logic, and real-world encapsulation patterns used in professional Python codebases.

What you'll learn in this chapter
Why encapsulation matters in OOP
Public, protected (_) and private (__) attributes
Name mangling — what __attr really does
@property — Pythonic getters and setters
@property.setter and @property.deleter
Real-world encapsulation design patterns
Advertisement

Why Encapsulation Matters

Without encapsulation, any part of your code can directly modify an object's internal state — leading to bugs that are hard to trace. Encapsulation solves this by defining a controlled interface: the class decides what can be read, what can be written, and how changes are validated.

Data Protection
Prevent invalid state changes
Abstraction
Hide implementation details
Validation
Validate data on write
Maintainability
Change internals safely
Python's approach to encapsulation Python uses naming conventions rather than strict access modifiers (unlike Java/C++). There is no private keyword — instead: no underscore = public, one underscore = "please don't touch", two underscores = name-mangled (harder to access accidentally). The @property decorator is Python's elegant way to add getter/setter logic without changing the public interface.

Three Access Levels — At a Glance

Python defines three access levels through naming conventions. The diagram below shows all three levels stacked vertically for easy comparison on any screen size:

Python Access Levels — Public → Protected → Private
Public name  (no underscore)
Accessible from anywhere — inside the class, subclasses, and outside. This is the default. Most attributes and methods should be public.
self.name = "Alice" → obj.name ✅ everywhere
Protected _name  (single underscore)
By convention, only the class and its subclasses should access this. Python does NOT enforce it — it's a developer signal: "internal use only." External access is possible but frowned upon.
self._salary = 50000 → obj._salary ⚠️ accessible but discouraged
Private __name  (double underscore)
Python applies name mangling — renames the attribute to _ClassName__name. This prevents accidental access or override from subclasses. Still technically accessible, but not by the original name.
self.__balance = 1000 → _Account__balance 🔒 name-mangled

Public Attributes & Methods

Public attributes and methods have no underscore prefix. They form the class's public API — what users of the class are expected to interact with. This is the default for all class members.

Python — public_attributes.py
class Person:
    def __init__(self, name, age):
        self.name = name        # public attribute
        self.age  = age         # public attribute

    def greet(self):           # public method
        return f"Hi, I'm {self.name}, {self.age} years old"

p = Person("Alice", 25)

# ✅ Read public attributes freely
print(p.name)          # Alice
print(p.age)           # 25
print(p.greet())       # Hi, I'm Alice, 25 years old

# ✅ Write public attributes freely
p.name = "Alicia"
p.age  = 26
print(p.greet())       # Hi, I'm Alicia, 26 years old

# Public = fully open interface — no restrictions

Protected Attributes (_single underscore)

A single leading underscore is a convention that signals: "this is for internal use — not part of the public API." Python does not enforce this — you can still access it from outside — but it's an important social contract that professional developers respect.

Python — protected_attributes.py
class Employee:
    def __init__(self, name, salary):
        self.name    = name         # public
        self._salary  = salary       # protected — internal use
        self._dept    = "Unknown"   # protected

    def get_info(self):            # public method uses protected data
        return f"{self.name} — {self._dept}"

    def _calculate_tax(self):      # protected method
        return self._salary * 0.2

class Manager(Employee):
    def promote(self):
        self._salary *= 1.1         # ✅ OK in subclass by convention
        self._dept    = "Management"

e = Employee("Alice", 50000)

# ⚠️ Technically accessible — but DON'T do this in production code
print(e._salary)          # 50000 — works, but bad practice

# ✅ Use the public interface instead
print(e.get_info())        # Alice — Unknown

m = Manager("Bob", 80000)
m.promote()
print(m.get_info())        # Bob — Management
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Private Attributes & Name Mangling

A double leading underscore triggers Python's name mangling — Python automatically renames __attr to _ClassName__attr. This prevents accidental overriding in subclasses. The attribute is still accessible via the mangled name, so it provides stronger protection than the single underscore convention — though it's still not truly private.

Python — private_name_mangling.py
class BankAccount:
    def __init__(self, owner, balance):
        self.owner     = owner          # public
        self.__balance = balance         # private — name-mangled to _BankAccount__balance
        self.__pin     = "0000"         # private

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            return True
        return False

    def get_balance(self):           # public method exposes private data safely
        return self.__balance

acc = BankAccount("Alice", 1000)

# ✅ Access via public method
acc.deposit(500)
print(acc.get_balance())    # 1500

# ❌ Direct access raises AttributeError
# print(acc.__balance)   → AttributeError: 'BankAccount' object has no attr '__balance'

# ⚠️ Still accessible via mangled name (but please don't!)
print(acc._BankAccount__balance)   # 1500 — via mangled name
print(acc.__dict__)               # {'owner': 'Alice', '_BankAccount__balance': 1500, ...}

# Name mangling protects against accidental override in subclasses
class SavingsAccount(BankAccount):
    def __init__(self, owner, balance, rate):
        super().__init__(owner, balance)
        self.__balance = 999            # ← becomes _SavingsAccount__balance — different!

s = SavingsAccount("Bob", 2000, 0.05)
print(s.get_balance())            # 2000 ← parent's __balance untouched!
Name mangling ≠ true privacy Python's __attr is not truly private — it can still be accessed via obj._ClassName__attr. Python's philosophy is "we're all consenting adults here" — the mangling is for accident prevention, not security. Never rely on it to protect sensitive data at runtime.

@property — Pythonic Getters, Setters & Deleters

The @property decorator is Python's clean, idiomatic way to add controlled access to an attribute without changing its external interface. Callers access it like a plain attribute (no parentheses), but under the hood a method runs — allowing validation, computation, and logging.

@property System — Getter, Setter, Deleter chain
self._temperature (private storage)
The actual value stored internally. Never accessed directly by the caller.
▼
@property → def temperature(self)
obj.temperature → calls the getter. Can compute or transform the value.
▼
@temperature.setter → def temperature(self, value)
obj.temperature = 25 → calls the setter. Validate before storing.
▼
@temperature.deleter → def temperature(self)
del obj.temperature → calls the deleter. Cleanup / reset logic.
Python — property_decorator.py
class Temperature:
    """Celsius temperature with validation."""

    def __init__(self, celsius=0.0):
        self.celsius = celsius          # ← uses the setter immediately!

    # ── Getter ──────────────────────────────────────────
    @property
    def celsius(self):
        return self._celsius

    # ── Setter — with validation ─────────────────────────
    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError(f"Temperature below absolute zero! ({value})")
        self._celsius = float(value)

    # ── Deleter ──────────────────────────────────────────
    @celsius.deleter
    def celsius(self):
        print("Deleting temperature — reset to 0")
        self._celsius = 0.0

    # ── Computed read-only property ──────────────────────
    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32

    @property
    def kelvin(self):
        return self._celsius + 273.15

# ── Using the class ───────────────────────────────────
t = Temperature(25)

# Read like a plain attribute — no parentheses!
print(t.celsius)      # 25.0     ← calls getter
print(t.fahrenheit)   # 77.0     ← computed property
print(t.kelvin)       # 298.15   ← computed property

# Write like a plain attribute — setter runs validation
t.celsius = 100
print(t.fahrenheit)   # 212.0

# ❌ Invalid value — setter raises ValueError
try:
    t.celsius = -300
except ValueError as e:
    print(e)           # Temperature below absolute zero! (-300)

# Delete triggers the deleter
del t.celsius          # "Deleting temperature — reset to 0"
print(t.celsius)       # 0.0

# Read-only property — no setter defined
# t.fahrenheit = 90  → AttributeError: can't set attribute

Real-World Encapsulation Patterns

Here's how encapsulation looks in professional Python code — a User model with controlled attribute access, computed properties, and validation built in:

Python — encapsulation_real_world.py
import re
import hashlib

class User:
    """User model with encapsulated email, age and password."""

    def __init__(self, username, email, age):
        self.username  = username       # public
        self.email     = email           # uses @email.setter
        self.age       = age             # uses @age.setter
        self.__password_hash = None     # private — never expose hash

    # ── email property with validation ───────────────────
    @property
    def email(self):
        return self._email

    @email.setter
    def email(self, value):
        if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w{2,}$', value):
            raise ValueError(f"Invalid email: {value}")
        self._email = value.lower().strip()

    # ── age property with validation ─────────────────────
    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if not (0 < value < 150):
            raise ValueError(f"Age must be 1-149, got {value}")
        self._age = int(value)

    # ── Computed read-only property ──────────────────────
    @property
    def is_adult(self):
        return self._age >= 18

    # ── Password — set only, never get ───────────────────
    def set_password(self, plain_password: str):
        if len(plain_password) < 8:
            raise ValueError("Password must be ≥ 8 characters")
        self.__password_hash = hashlib.sha256(
            plain_password.encode()
        ).hexdigest()

    def check_password(self, plain_password: str) -> bool:
        return self.__password_hash == hashlib.sha256(
            plain_password.encode()
        ).hexdigest()

    def __str__(self):
        return f"User({self.username}, {self._email}, adult={self.is_adult})"

# ── Usage ─────────────────────────────────────────────
u = User("alice", "alice@example.com", 25)
u.set_password("SecurePass1")

print(u.email)                         # alice@example.com
print(u.is_adult)                      # True
print(u.check_password("SecurePass1")) # True
print(u.check_password("wrong"))       # False
print(u)

# ❌ Invalid email raises ValueError
try:
    u.email = "not-valid"
except ValueError as e:
    print(e)                            # Invalid email: not-valid

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all encapsulation examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every encapsulation example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Encapsulation bundles data and methods in a class and controls external access — enabling data protection, validation, and abstraction.
  • Python uses naming conventions for access control: no underscore = public, _name = protected (convention only), __name = private (name-mangled).
  • Public attributes/methods: accessible everywhere. The default — no underscore needed.
  • Protected (_name): a convention signal meaning "internal use only for this class and subclasses." Python does not enforce it.
  • Private (__name): Python applies name mangling — renames to _ClassName__name. Prevents accidental overriding in subclasses. Still accessible via the mangled name.
  • The @property decorator creates a getter — accessed like an attribute (no parentheses). Add @name.setter for write access with validation, @name.deleter for delete logic.
  • Properties let you change internal implementation without breaking the external interface — start with a plain attribute, add @property later if needed.
  • Computed/read-only properties: define @property without a setter. Any attempt to set raises AttributeError.
  • Best practice: store validated data in _attr, expose it through @property with full validation logic in the setter.
Free Resource
Download our Python Encapsulation Cheat Sheet
Public/protected/private, name mangling, @property getter/setter/deleter & patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Python uses naming conventions (not keywords) to indicate access level:

  • Public (name) — no prefix. Accessible from anywhere. The default for all class members.
  • Protected (_name) — single underscore prefix. Convention only — "internal use, not for public API". Still externally accessible in Python.
  • Private (__name) — double underscore prefix. Python applies name mangling (renames to _ClassName__name) to prevent accidental override in subclasses.
✓ Answer

Name mangling is Python's automatic renaming of an attribute that starts with two underscores: __attr inside class Foo becomes _Foo__attr.

The problem it solves: without mangling, a subclass that accidentally defines __balance would overwrite the parent's __balance. With mangling, parent's becomes _Parent__balance and child's becomes _Child__balance — they never collide.

The attribute is still accessible as obj._ClassName__attr — it is not truly private in the cryptographic sense.

✓ Answer

The @property decorator turns a method into a descriptor that behaves like an attribute. The caller accesses it as obj.attr (no parentheses), but internally a method runs.

Why use it? You can start with a plain attribute, then add validation/computation later with @property — without breaking any existing code that uses the attribute. The caller's interface never changes.

# Caller code — same whether plain attr or property
print(t.temperature)    # reads via getter
t.temperature = 25      # writes via setter (with validation)
✓ Answer

Define @property for the getter but do not define a @name.setter. Any attempt to set the value will raise AttributeError: can't set attribute.

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):              # read-only computed property
        import math
        return math.pi * self.radius ** 2

# c.area = 50  → AttributeError
✓ Answer

_attr (single underscore) is a convention only — it signals "this is internal, please don't use it from outside." Python does nothing special to enforce it. External code can still access obj._attr freely.

__attr (double underscore) triggers name mangling — Python actively renames it to _ClassName__attr. This means obj.__attr raises AttributeError from outside the class. It is still accessible via the mangled name, but the double underscore provides stronger (though not absolute) protection and prevents subclass collision.

MCQ 1 of 3
Given class Foo: def __init__(self): self.__x = 5, what is the mangled name of __x?
MCQ 2 of 3
Which decorator is used to define a setter for a property named age?
MCQ 3 of 3
What happens when you define @property for an attribute but do NOT define a setter?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel