Loading

Quipoin Menu

Learn • Practice • Grow

python / Encapsulation
tutorial

Encapsulation

Encapsulation hides internal data and implementation details, exposing only what is necessary. In Python, we use naming conventions to indicate private attributes (prefix with underscore `_`) and name mangling (double underscore `__`) to make them less accessible. Unlike Java, Python does not have true private members, but by convention these should be treated as non‑public.

Public, Protected, Private Conventions
  • Public: `self.name` – accessible everywhere.
  • Protected (internal use): `self._name` – by convention, treat as non‑public.
  • Private (name mangling): `self.__name` – name is mangled to `_ClassName__name` to avoid accidental overriding.

class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # public
self._account_type = "savings" # protected (convention)
self.__balance = balance # private (name mangling)

def deposit(self, amount):
if amount > 0:
self.__balance += amount

def get_balance(self):
return self.__balance

Accessing Name‑mangled Attributes
They are still accessible as `_ClassName__attr`, but this is discouraged.
Two Minute Drill
  • Encapsulation hides internal state using naming conventions.
  • Single underscore `_` indicates protected (internal use).
  • Double underscore `__` triggers name mangling (stronger privacy).
  • Provide getter/setter methods to control access.
  • Python emphasizes convention over enforcement.

Need more clarification?

Drop us an email at career@quipoinfotech.com