What is Encapsulation in Python: Simple Explanation and Example
encapsulation means hiding the internal details of an object and only exposing what is necessary through methods. It helps protect data by restricting direct access to some of an object's components.How It Works
Encapsulation in Python works like a protective shield around an object's data. Imagine a TV remote control: you press buttons without seeing the complex circuits inside. Similarly, encapsulation hides the internal variables and only allows interaction through specific methods.
This is done by marking variables as private using underscores (e.g., _variable or __variable). These private variables cannot be accessed directly from outside the class, which helps prevent accidental changes and keeps the data safe.
Example
This example shows a class with a private variable and methods to get and set its value safely.
class BankAccount: def __init__(self, balance): self.__balance = balance # Private variable def deposit(self, amount): if amount > 0: self.__balance += amount def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount def get_balance(self): return self.__balance account = BankAccount(100) account.deposit(50) account.withdraw(30) print(account.get_balance())
When to Use
Use encapsulation when you want to protect important data inside your objects from being changed directly. This is useful in real-world cases like bank accounts, user profiles, or settings where you want to control how data is updated.
It helps avoid bugs by making sure data changes happen only through controlled methods, keeping your program more reliable and easier to maintain.
Key Points
- Encapsulation hides internal data using private variables.
- Access to data is controlled through public methods.
- It protects data from accidental or unauthorized changes.
- Python uses underscores to indicate private variables.
- Encapsulation improves code reliability and maintenance.