Skip to content

Module 11 · Object-Oriented Programming — topic 14 of 25

Encapsulation

Protecting an object's state: public, 'protected' (_name) and name-mangled (__name) attributes, controlled access through methods and properties, and Python's 'consenting adults' philosophy.

Beginner 10 min read·Lesson 171 of 306 in Python Programming

Learning objectives

  • Mark internal attributes with _ and __
  • Expose safe operations instead of raw data
  • Explain name mangling and its purpose

Definition

Encapsulation is bundling data with the methods that operate on it and restricting direct access to the data, so the object can maintain its own rules. Python enforces this by convention rather than strict access modifiers.

Introduction

A bank wouldn't let you edit your balance directly — you deposit and withdraw, and the bank applies the rules. Encapsulation gives your objects the same protection.

Why it matters

When anyone can change an object's data, nobody can guarantee it is valid. Encapsulation keeps rules in one place and lets you change internals later without breaking users of the class.

Detailed explanation

Python has no private keyword. Instead, a single leading underscore (_balance) means 'internal — don't touch from outside'. Tools and readers respect it, but Python doesn't enforce it.

A double leading underscore (__balance) triggers name mangling: inside class Account it becomes _Account__balance. This avoids accidental name clashes in subclasses; it is not real security.

The public interface is the set of methods and attributes meant for outside use. Keep it small and stable.

Expose operations (deposit, withdraw) rather than setters for raw values, and use properties (see Properties) when attribute-like access needs validation.

Python's philosophy is 'we are all consenting adults': conventions signal intent, and developers are trusted to follow them.

Syntax

Python
class Account:
def __init__(self, owner):
self.owner = owner # public
self._balance = 0 # internal (convention)
self.__pin = "0000" # name-mangled
@property
def balance(self): # read-only public view
return self._balance
  • _name: internal by convention.
  • __name: mangled to _Class__name.
  • Expose methods/properties, not raw data.

Code examples

Controlled access

Python
class Account:
def __init__(self, owner):
self.owner = owner
self._balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self._balance += amount
def balance(self):
return self._balance
a = Account("Asha")
a.deposit(500)
print(a.balance())
try:
a.deposit(-100)
except ValueError as e:
print(e)
Output
500
deposit must be positive

Name mangling

Python
class Vault:
def __init__(self):
self.__code = "1234"
def check(self, guess):
return guess == self.__code
v = Vault()
print(v.check("1234"))
print(hasattr(v, "__code"), hasattr(v, "_Vault__code"))
Output
True
False True

More examples

Changing internals without breaking users

Python
class Temperature:
"""Stores kelvin internally but offers a Celsius interface."""
def __init__(self, celsius):
self.set_celsius(celsius)
def set_celsius(self, c):
if c < -273.15:
raise ValueError("below absolute zero")
self._kelvin = c + 273.15
def celsius(self):
return round(self._kelvin - 273.15, 2)
def fahrenheit(self):
return round(self.celsius() * 9 / 5 + 32, 2)
t = Temperature(25)
print(t.celsius(), t.fahrenheit())
t.set_celsius(-40)
print(t.celsius(), t.fahrenheit())
try:
t.set_celsius(-300)
except ValueError as e:
print(e, "| still", t.celsius())
Output
25.0 77.0
-40.0 -40.0
below absolute zero | still -40.0

Step-by-step explanation

  • The object stores kelvin in _kelvin, but users only see Celsius and Fahrenheit methods.
  • set_celsius validates before storing, so the object can never hold an impossible temperature.
  • The internal unit could change later without affecting any calling code.

Expected output

Running “Changing internals without breaking users” prints exactly:

TextOutput
25.0 77.0
-40.0 -40.0
below absolute zero | still -40.0

Practical applications

  • Library classes keep internal helpers prefixed with _.
  • Frameworks validate model fields through setters or properties.

Best practices

  • Prefix internal attributes with a single underscore.
  • Expose behaviour, not raw state.
  • Validate in the methods that change state.

Common mistakes

Treating __ as security

Avoid

self.__password = pw # 'nobody can read this'

Prefer

Store a hash and never expose it; mangling is only a naming aid.

Mangled names can still be read as _Class__password.

Getters and setters for everything

Avoid

def get_name(self): ...
def set_name(self, v): ...

Prefer

Use a plain attribute, and a property only when logic is needed.

Python doesn't need Java-style boilerplate; properties can be added later without changing callers.

Important notes

  • Attributes starting with _ are excluded from from module import *.

Key takeaways

  • Encapsulation protects an object's rules.
  • _name is internal by convention; __name is mangled.
  • Expose operations and properties, not raw data.

Try it yourself

  1. 1
    Encapsulate a Thermostat so the target can only be set between 16 and 30.
  2. 2
    Show that a __private attribute can still be reached as _ClassName__private and explain why it exists.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic