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.
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.
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:
_ClassName__name. This prevents accidental access or override from
subclasses. Still technically accessible, but not by the original name.
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.
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.
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
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.
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!
__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.
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:
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.
- 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
@propertydecorator creates a getter — accessed like an attribute (no parentheses). Add@name.setterfor write access with validation,@name.deleterfor delete logic. - Properties let you change internal implementation without breaking the external interface — start with a
plain attribute, add
@propertylater if needed. - Computed/read-only properties: define
@propertywithout a setter. Any attempt to set raisesAttributeError. - Best practice: store validated data in
_attr, expose it through@propertywith full validation logic in the setter.
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.
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.
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)
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
_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.
class Foo: def __init__(self): self.__x = 5,
what is the mangled name of __x?age?@property for an
attribute but do NOT define a setter?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.