Encapsulation is one of the core principles of Object-Oriented Programming (OOP). It means binding data (variables) and
methods (functions) that operate on that data within a single unit — a
class.
It also helps in restricting direct access to the internal state of an object — protecting data from unintended modification.
In Python, encapsulation is implemented using:
Public members – accessible from anywhere.
Protected members – prefix with _ (single underscore), meant for internal use.
Private members – prefix with __ (double underscore), not accessible directly from outside the class.
Example of Encapsulation
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # Public attribute
self._account_type = "Saving" # Protected attribute
self.__balance = balance # Private attribute
# Public method
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited: {amount}")
else:
print("Invalid amount")
# Public method to view balance (controlled access)
def get_balance(self):
return self.__balance
# Public method to withdraw money
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
print(f"Withdrawn: {amount}")
else:
print("Insufficient balance")
# Create object
account = BankAccount("Anna", 5000)
# Access public attribute
print("Owner:", account.owner)
# Access protected attribute (possible but discouraged)
print("Account Type:", account._account_type)
# Access private attribute directly (Not allowed)
# print(account.__balance) # AttributeError
# Access private data using public method (Encapsulated access)
print("Balance:", account.get_balance())
account.deposit(1000)
account.withdraw(2000)
print("Updated Balance:", account.get_balance())
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
It also helps in restricting direct access to the internal state of an object — protecting data from unintended modification.
In Python, encapsulation is implemented using:
_(single underscore), meant for internal use.__(double underscore), not accessible directly from outside the class.Example of Encapsulation
Output
Why Encapsulation is Important
Accessing Private Variables (Name Mangling)
Even though private variables are not directly accessible, Python internally renames them: