Encapsulation & Name Mangling in Python
1. What is Encapsulation?
Encapsulation in OOP means:
- Bundling data (variables) and behavior (methods) together
- Restricting direct access to internal data
- Exposing only a controlled interface
Think of it like a capsule — it wraps and protects its contents.
Encapsulation is the OOP principle of bundling data and methods that operate on that data into a single unit, while restricting direct access to the internal state. It maintains data integrity, reduces coupling, and allows internal implementation to change without affecting external code.
Real-world analogy:
A car exposes a steering wheel and pedals but hides the engine. You control the car without knowing how the engine works.
2. Python & Encapsulation
variable→ Public_variable→ Protected (convention)__variable→ Private (name-mangled)
3. Name Mangling
Name mangling automatically changes attributes starting with __ to include the class name:
class Person:
def __init__(self):
self.__salary = 50000
Internally:
__salary → _Person__salary
This prevents accidental access and subclass collisions, but does not enforce true privacy.
Accessing name-mangled variables:
p = Person()
print(p.__salary) # Error
print(p._Person__salary) # Works
4. Why Encapsulation Still Works in Python
- It prevents accidental access
- It avoids subclass collisions
- It signals strong intent — accessing mangled variables is intentional
Encapsulation in Python is about design and intent, not absolute secrecy.
"Even though Python allows access to name-mangled variables, encapsulation is preserved because it relies on convention and intent rather than strict enforcement. Name mangling prevents accidental access and name collisions, while still allowing advanced users to access internals when absolutely necessary."
5. Summary
| Language | Encapsulation Style |
|---|---|
| Java / C++ | Enforced by compiler |
| Python | Enforced by convention |
Encapsulation protects object integrity by exposing behavior, not data.