Think about an ATM. You can check your balance, deposit money and withdraw money using a few buttons. But you can't open the machine and change the number stored for your account. The ATM hides its internal details and only gives you a safe set of actions.
This idea is called encapsulation, and it is one of the four pillars of Object-Oriented Programming (along with inheritance, polymorphism and abstraction). In this chapter you'll learn how Python handles it, which is a little different from languages like Java or C++.
What is Encapsulation?
Encapsulation means bundling data (attributes) and the methods that work on that data inside a class, and controlling how that data can be accessed or changed from outside.
It gives us two benefits:
Protection - the object can stop invalid values (like a negative balance) from being stored.
Freedom to change - the class can change how it stores data internally without breaking the code that uses it.
Let's first see the problem encapsulation solves.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
acc = BankAccount("Riya", 1000)
acc.balance = -5000 # nothing stops this!
print(acc.balance)Output:
-5000Anyone can put any value into balance. A bank account with -5000 rupees created by a typo is a bug waiting to happen.
Python's Approach: Conventions, Not Locks
Java has keywords like private, protected and public that the compiler enforces. Python has no such keywords. Instead, it uses naming conventions:
Name | Meaning | Enforced? |
|---|---|---|
| Public - free to use from anywhere | - |
| "Protected" / internal - please don't touch from outside | No, just a convention |
| "Private" - Python renames it (name mangling) | Partly - harder to access by accident |
Python's philosophy is often described as "we are all consenting adults here". The language trusts programmers to respect these signals instead of building walls.
Protected Members: Single Underscore
A single leading underscore tells other programmers: "this is an internal detail, use it at your own risk."
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self._balance = balance # internal
acc = BankAccount("Riya", 1000)
print(acc._balance) # works, but you shouldn't do thisOutput:
1000Python does not stop you. The underscore is only a message. Subclasses are expected to use _ members, which is why this is called "protected".
One small real effect: from module import * skips module-level names that start with an underscore (unless the module lists them in __all__).
Private Members: Double Underscore
When an attribute name starts with two underscores (and does not end with two underscores), Python changes its name behind the scenes. This is called name mangling.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance
acc = BankAccount("Riya", 1000)
print(acc.__balance)Output:
AttributeError: 'BankAccount' object has no attribute '__balance'The attribute exists, but under a different name. Inside the class, self.__balance is automatically rewritten as self._BankAccount__balance:
You write (inside class BankAccount) Python stores it as
----------------------------------- --------------------
self.__balance ---> self._BankAccount__balanceclass BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance
acc = BankAccount("Riya", 1000)
print(acc._BankAccount__balance) # the mangled name still works
print(acc.__dict__)Output:
1000
{'owner': 'Riya', '_BankAccount__balance': 1000}So double underscore is not real security. It just makes accidental access much less likely.
Why Name Mangling Exists
The real purpose of name mangling is to avoid name clashes in subclasses. If a parent and child both use __id, they get separate attributes:
class Parent:
def __init__(self):
self.__id = "parent-id"
class Child(Parent):
def __init__(self):
super().__init__()
self.__id = "child-id" # does NOT overwrite Parent's __id
c = Child()
print(c.__dict__)Output:
{'_Parent__id': 'parent-id', '_Child__id': 'child-id'}Note that special names like __init__ and __str__ end with two underscores, so they are not mangled.
Getters and Setters
To control access, we expose methods that read and update the hidden data. The setter can validate values before storing them.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount <= 0:
print("Deposit must be positive")
return
self.__balance += amount
def withdraw(self, amount):
if amount > self.__balance:
print("Insufficient balance")
return
self.__balance -= amount
acc = BankAccount("Riya", 1000)
acc.deposit(500)
acc.withdraw(5000)
acc.deposit(-20)
print(acc.get_balance())Output:
Insufficient balance
Deposit must be positive
1500The balance can now change only through deposit() and withdraw(), which always check the rules.
The Pythonic Way: @property
Writing get_x() and set_x() for every attribute is common in Java, but in Python it feels clumsy. Python offers @property, which lets you keep simple attribute syntax (obj.age) while still running a method behind the scenes.
The @ symbol is called a decorator. You'll learn how decorators work in a later chapter; for now, just use the pattern below.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age # this already goes through the setter
@property
def age(self): # getter
return self._age
@age.setter
def age(self, value): # setter
if not 0 < value < 120:
raise ValueError("Age must be between 1 and 119")
self._age = value
s = Student("Aman", 20)
print(s.age) # looks like an attribute, calls the getter
s.age = 21 # calls the setter
print(s.age)
try:
s.age = -5
except ValueError as e:
print("Error:", e)Output:
20
21
Error: Age must be between 1 and 119Notice that even __init__ uses the setter, so an invalid age is rejected right at object creation too.
Read-Only and Computed Properties
If you define only the getter, the property becomes read-only. Properties are also great for values that are calculated from other attributes.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
r = Rectangle(4, 5)
print(r.area)
r.width = 10
print(r.area) # always up to date
try:
r.area = 100
except AttributeError as e:
print("Error:", e)Output:
20
50
Error: property 'area' of 'Rectangle' object has no setterWhy Properties Are So Useful
Start with a plain public attribute. If you later need validation, convert it into a property. The code using your class (obj.age = 21) does not need to change at all. This is why Python programmers don't write getters and setters "just in case".
Common Mistakes
1. Using the same name inside the property
class Student:
@property
def age(self):
return self.age # calls the getter again... forever
s = Student()
print(s.age)Output:
RecursionError: maximum recursion depth exceededStore the real value in a different name, usually with an underscore: self._age.
2. Thinking __ makes data secure
Name mangling only renames the attribute. Anyone can still reach obj._ClassName__attr. Never rely on it to hide passwords or secrets.
3. Writing getters/setters for everything
If a getter just returns the value and a setter just stores it, a plain public attribute is simpler and more Pythonic.
4. Mangled names in subclasses
A child class cannot access the parent's self.__x by writing self.__x, because inside the child it becomes self._Child__x. Use a single underscore if subclasses need access.
Interview Tips
Does Python have private variables? Not truly. It has conventions (
_x) and name mangling (__xbecomes_ClassName__x).Difference between
_xand__x?_xis purely a convention.__xtriggers name mangling, mainly to avoid clashes in subclasses.Why use
@property? It adds validation or computation while keeping attribute syntax, so you can change the implementation without breaking callers.Encapsulation vs abstraction? Encapsulation is about hiding and protecting data inside a class. Abstraction is about hiding complexity and showing only the essential features.
Summary
Encapsulation bundles data with the methods that use it and controls access to that data.
Python uses naming conventions instead of access keywords:
name(public),_name(internal),__name(name-mangled).Name mangling rewrites
__nameas_ClassName__name; it prevents accidents, not determined access.@propertyis the Pythonic way to add getters, setters, validation, read-only and computed attributes.
In Python, encapsulation is a promise between programmers, not a lock. Respect the underscore, and use properties when you need control.