Last modified: Dec 05, 2026
Types of Encapsulation in Python
Python doesn't have real private variables. That surprises a lot of people coming from Java or C++. Instead, it gives you conventions and a bit of name mangling, and it trusts you to follow the rules. If you've read about encapsulation in Python OOP, you already know the basic idea: hide internal state and expose only what's needed.
But "encapsulation" isn't one thing. There are several levels and styles you'll run into. Here's a practical breakdown of each type, with code you can actually run.
1. Public Members: The Default
Everything in Python is public unless you say otherwise. No keyword, no modifier, no ceremony. You just write an attribute and anyone can read or change it.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # public attribute
self.balance = balance # public attribute
def show_balance(self): # public method
return self.balance
acct = BankAccount("Mia", 500)
print(acct.balance)
acct.balance = 9999 # nothing stops you
print(acct.show_balance())
500
9999
Is that bad? Not always. For small scripts and plain data holders, public attributes are fine. But once other code starts poking at your objects, you'll want a boundary.
2. Protected Members: The Single Underscore
Prefix an attribute with one underscore and you're telling other developers "this is internal, touch it at your own risk." Python won't block access. It's a hint, nothing more.
class Employee:
def __init__(self, name, salary):
self.name = name
self._salary = salary # protected by convention
def get_salary(self):
return self._salary
emp = Employee("Leo", 4200)
print(emp.get_salary())
print(emp._salary) # works, but you shouldn't
4200
4200
Subclasses are expected to use these. Outside code isn't. I like this convention a lot — it's low friction and works well in teams that review each other's code. If you want to see how subclasses interact with protected members, the encapsulation in Python classes guide covers it nicely.
3. Private Members: Name Mangling
Two underscores and Python actually does something. It renames the attribute behind the scenes. That's called name mangling, and it's the closest thing Python has to private.
class Vault:
def __init__(self, code):
self.__code = code # mangled to _Vault__code
def check(self, attempt):
return attempt == self.__code
v = Vault("1234")
print(v.check("1234"))
print(v.__code) # AttributeError
True
AttributeError: 'Vault' object has no attribute '__code'
Note the error. Accessing __code from outside fails because the real name is _Vault__code. Still, it's not real security — you can reach it with the mangled name if you really want. It's a speed bump, not a lock.
One gotcha worth knowing: mangling also affects inheritance. A subclass can't easily override a double-underscore attribute. That's usually what you want, but it trips people up.
4. Encapsulation Through Properties
This is where Python gets elegant. Properties let you keep the clean obj.attr syntax while running validation or logic under the hood. The @property decorator turns a method into a readable attribute.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Below absolute zero")
self._celsius = value
t = Temperature(20)
print(t.celsius)
t.celsius = 25
print(t.celsius)
t.celsius = -300 # raises ValueError
20
25
ValueError: Below absolute zero
Properties are my go-to for encapsulation in real projects. You get validation without breaking the API. Users still write t.celsius = 25, and you control what happens behind that assignment.
5. Encapsulation in Methods and Helper Functions
It's not just about attributes. You can hide logic inside private methods too. A single underscore on a method signals that it's an internal helper.
class Report:
def __init__(self, rows):
self.rows = rows
def _clean(self):
return [r.strip() for r in self.rows if r]
def render(self):
data = self._clean() # internal helper
return " | ".join(data)
print(Report([" a ", "", "b "]).render())
a | b
The public surface is just render. Everything else is an implementation detail you can change later without breaking callers.
How Encapsulation Interacts With Inheritance
Encapsulation and inheritance don't always play nicely. Private (mangled) members stay with the parent class, while protected members flow down to children. That matters when you design class hierarchies.
If you're building subclasses and want to understand the interaction, the material on Python inheritance and polymorphism explains how overrides and access levels work together. Polymorphism also depends on clean interfaces, which is really what encapsulation is about.
Quick Comparison
- Public — no prefix, free access, use for stable API.
- Protected — single underscore, convention only, intended for subclasses.
- Private — double underscore, name mangled, hard to reach from outside.
- Properties — controlled access with validation, best for real projects.
Which Type Should You Use?
Start simple. Use public attributes until something needs protection. Then reach for a single underscore when you want to signal intent, and properties when you need validation or computed values. Double underscores are rare — use them when you genuinely want to prevent accidental overrides in subclasses.
Don't over-engineer. I've seen codebases where every single attribute is double-underscore private, and it just makes debugging painful. Python isn't Java. The culture here is trust plus clear naming.
One more thing: encapsulation is about design, not enforcement. The goal is a class that's easy to use correctly and hard to misuse. If your object exposes a small, obvious interface, you're doing it right.
Conclusion
Python gives you several encapsulation styles: public members, protected members with a single underscore, private members with name mangling, and properties for controlled access. Each has a place.
Pick the lightest tool that solves your problem, and lean on properties when you need real validation. That's the practical path, and it keeps your classes readable for everyone who touches them later.