By WebNest Studio Engineering Team
Python Tutorial
Encapsulation and Access Modifiers in Python
Encapsulation means bundling data with the methods that operate on it and hiding internal details behind a clear interface. A bank account should not let anyone set its balance to any value; changes should go through deposit() and withdraw(), which enforce the rules.
Python has no private or protected keywords. Instead it uses naming conventions — public names, _protected names and __private names with name mangling — together with properties. This lesson explains all three levels and how to design well-encapsulated classes.
Why it matters
An object that lets any code change its data directly cannot guarantee that the data stays valid: a bank balance could be set to a negative number from anywhere. Encapsulation puts the rules in one place. Python does this by convention and with properties, not with keywords such as private, which is a common source of confusion.
Public, Protected and Private by Convention
The three levels:
- Public —
name: part of the class's interface; anyone may use it. - Protected —
_name: "internal, please don't touch from outside"; subclasses may use it. Nothing stops access — it is a convention every Python developer respects.from module import *also skips such names. - Private —
__name: Python name-mangles it to_ClassName__name, preventing accidental access and name clashes in subclasses. It is still reachable through the mangled name, so it is not true security.
Controlled Access with Methods and Properties
Expose behaviour, not raw data: methods validate changes, and @property lets you provide read-only or validated attributes while keeping attribute syntax (see the properties lesson). This way you can change the internal representation later without breaking code that uses the class.
Why Encapsulate
Encapsulation protects invariants (a balance never goes negative), reduces coupling (callers depend on a small interface), and makes refactoring safe. "We are all consenting adults" is the Python philosophy: conventions communicate intent, and developers respect them.
Examples
Public, protected and private attributes
class Account:
def __init__(self, owner, balance):
self.owner = owner # public
self._branch = "Pune" # protected (internal)
self.__balance = balance # private (name-mangled)
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self.__balance += amount
def withdraw(self, amount):
if amount > self.__balance:
raise ValueError("insufficient funds")
self.__balance -= amount
def balance(self):
return self.__balance
acc = Account("Asha", 1000)
acc.deposit(500)
print(acc.owner, acc._branch, acc.balance())
try:
print(acc.__balance)
except AttributeError as e:
print("AttributeError:", e)
print(vars(acc))
print(acc._Account__balance) # mangled name still exists
Asha Pune 1500
AttributeError: 'Account' object has no attribute '__balance'
{'owner': 'Asha', '_branch': 'Pune', '_Account__balance': 1500}
1500
Name mangling prevents clashes in subclasses
class Parent:
def __init__(self):
self.__secret = "parent"
self._shared = "parent"
class Child(Parent):
def __init__(self):
super().__init__()
self.__secret = "child" # a different attribute: _Child__secret
self._shared = "child" # overwrites the parent's
c = Child()
print(sorted(vars(c).items()))
[('_Child__secret', 'child'), ('_Parent__secret', 'parent'), ('_shared', 'child')]
Encapsulating with a read-only property and validated setter
class Employee:
def __init__(self, name, salary):
self._name = name
self.salary = salary # goes through the setter
@property
def name(self): # read-only
return self._name
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, value):
if value < 0:
raise ValueError("salary cannot be negative")
self._salary = value
e = Employee("Kiran", 50000)
e.salary = 55000
print(e.name, e.salary)
for action in (lambda: setattr(e, "salary", -1), lambda: setattr(e, "name", "X")):
try:
action()
except (ValueError, AttributeError) as err:
print(type(err).__name__, "-", err)
Kiran 55000
ValueError - salary cannot be negative
AttributeError - property 'name' of 'Employee' object has no setter
Common Mistakes
- Believing __private attributes are secure; they are only name-mangled.
- Writing Java-style get_x()/set_x() for every attribute instead of plain attributes or properties.
- Accessing another class's _protected attributes from outside it.
- Exposing internal mutable lists directly so callers can bypass validation.
Exercise
Write a BankAccount class that keeps its balance in a private attribute, accepts deposits of positive amounts only, and exposes the balance through a read-only property.
Expected output: 500, read-only, False (one per line)
class BankAccount:
def __init__(self):
self.__balance = 0
# TODO: deposit(amount) that raises ValueError unless amount > 0
# TODO: a read-only property named balance
account = BankAccount()
account.deposit(500)
print(account.balance)
try:
account.balance = 0
except AttributeError:
print("read-only")
print(hasattr(account, "__balance"))
Show hints
- A method decorated with
@propertyis read like an attribute. - With no setter defined, assigning to the property raises
AttributeError.
Show solution
class BankAccount:
def __init__(self):
self.__balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.__balance += amount
@property
def balance(self):
return self.__balance
account = BankAccount()
account.deposit(500)
print(account.balance)
try:
account.balance = 0
except AttributeError:
print("read-only")
print(hasattr(account, "__balance"))
Quick quiz
1. What does a single leading underscore, as in _cache, mean?
- A. Python blocks access from outside the class
- B. The attribute is static
- C. A convention: the attribute is internal and should not be used from outside
- D. The attribute is constant
Show answer
C. Nothing is enforced. It is a signal to other programmers.
2. Inside class Account, an attribute is written as self.__pin. Under what name is it actually stored?
- A. __pin
- B. Account.pin
- C. _pin
- D. _Account__pin
Show answer
D. This renaming is called name mangling.
3. Does Python have truly private attributes?
- A. No; privacy is by convention, and mangled names can still be reached
- B. Yes, with the private keyword
- C. Yes, with a double underscore
- D. Only in abstract classes
Show answer
A. The language relies on convention, not on enforcement.
Interview questions
How is encapsulation achieved in Python?
Show answer
By convention and by properties. A name starting with one underscore is treated as internal. A name starting with two underscores is mangled to include the class name, which prevents accidental access and clashes in subclasses. Access that needs rules is given through methods or a @property, so validation happens in one place while the attribute is still used with plain attribute syntax.
What is name mangling and what is it for?
Show answer
An attribute named with two leading underscores inside a class, such as __balance, is stored as _ClassName__balance. Its main purpose is to stop a subclass from accidentally overwriting an attribute of its parent by choosing the same name. It is not a security feature, since the mangled name can still be used from outside.
Key Points to Remember
- Python uses conventions: public, _protected, __private.
- __name is name-mangled to _Class__name, avoiding clashes but not providing security.
- Expose behaviour through methods and properties that enforce rules.
- Encapsulation protects invariants and allows internal changes without breaking callers.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering