Lesson 28 of 55
PythonOOP – Encapsulation
20 minutes
Course progress51%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 28 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
Encapsulation hides an object's internal state and forces interaction through a defined public interface. In Python, a leading double underscore triggers name‑mangling, making an attribute harder to access from outside.
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # private attribute
@property
def balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
account = BankAccount(100)
account.deposit(50)
print('Balance:', account.balance) # 150
The balance property is read‑only from the outside; only deposit can modify the underlying private attribute.