Encapsulation with Getters/Setters in Python
Use properties to encapsulate attribute access with getter and setter logic.
IntermediateObject-Oriented ProgramsExample 9 of 25
encapsulation-with-getters-setters.py
Run in browser1# Program to demonstrate encapsulation using properties23class Account:4 def __init__(self, balance=0):5 self._balance = balance67 @property8 def balance(self):9 return self._balance1011 @balance.setter12 def balance(self, amount):13 if amount < 0:14 raise ValueError("Balance cannot be negative")15 self._balance = amount1617acc = Account(100)18print(acc.balance)19acc.balance = 15020print(acc.balance)
Output
100 150
What's going on
The @property decorator allows attribute-style access while still enforcing validation in the setter.