Encapsulation in Python is the practice of hiding an object’s internal state and requiring all interactions to be performed through methods.
This helps protect data, improves code security, and makes programs more maintainable.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
Here:
__balance
is a private attribute (not directly accessible outside the class).deposit()
andget_balance()
are public methods that control access to the private data.
👉 Next tutorial: Python Access Modifiers