Back to Study Material Python

Encapsulation

Encapsulation is the practice of bundling data and the methods that operate on it inside a single unit, the class, and controlling how that data is accesse...

Encapsulation

Encapsulation in Python: Controlling Access to Object Data

Encapsulation is the practice of bundling data and the methods that operate on it inside a single unit, the class, and controlling how that data is accessed from outside. The goal is to protect the internal state of an object from being changed in unexpected ways and to present a clean interface to the rest of the program.

Python does not have truly private attributes in the way that Java or C++ do. Instead, it uses naming conventions to signal intent. A single leading underscore, such as _balance, means "treat this as internal; use it at your own risk." A double leading underscore, such as __balance, triggers name mangling, which makes it harder (but not impossible) to access from outside the class.

class BankAccount: def __init__(self, owner, balance): self.owner = owner self.__balance = balance # name-mangled

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

def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount else: raise ValueError("Insufficient funds or invalid amount")

def get_balance(self): return self.__balance

account = BankAccount("Alice", 500) account.deposit(200) print(account.get_balance()) # 700

Trying to access account.__balance directly from outside the class will raise an AttributeError because Python renames it internally to _BankAccount__balance. This protects the balance from being accidentally overwritten with invalid data.

Encapsulation is most valuable when you need to enforce invariants. In the example above, the deposit and withdraw methods validate input before changing the balance. If __balance were public, any code could set it to a negative number or a string, breaking the account logic.

Python also supports properties, which let you define getter and setter methods that look like regular attribute access from outside. This gives you the clean syntax of direct access while preserving the control of encapsulation.

Exam tip: Know that Python's name mangling transforms __attr into _ClassName__attr. It is a hint to developers, not a security feature. A determined programmer can still access it. Mention this in exams to show you understand the difference between Python's conventions and strict access modifiers in other languages.