Python Practice › OOP Programs › Program 16
Encapsulation with a private attribute
Write a Python program that demonstrates encapsulation.
Output
1500 False
Approach
- Keep the balance in a “private” attribute and change it only through methods.
Solution
class Account: def __init__(self, balance): self.__balance = balance def deposit(self, amount): if amount > 0: self.__balance += amount def balance(self): return self.__balance a = Account(1000)a.deposit(500)a.deposit(-50)print(a.balance())print(hasattr(a, "__balance"))Output
1500 False
Line by line
Line 3
Two leading underscores trigger name mangling, so the attribute is hard to reach from outside.
Line 6
The method validates input, so the balance can never be decreased by a negative deposit.
Learn the concept
New to this topic? Read the lesson, then come back.