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 browser
1# Program to demonstrate encapsulation using properties
2
3class Account:
4 def __init__(self, balance=0):
5 self._balance = balance
6
7 @property
8 def balance(self):
9 return self._balance
10
11 @balance.setter
12 def balance(self, amount):
13 if amount < 0:
14 raise ValueError("Balance cannot be negative")
15 self._balance = amount
16
17acc = Account(100)
18print(acc.balance)
19acc.balance = 150
20print(acc.balance)

Output

100
150

What's going on

The @property decorator allows attribute-style access while still enforcing validation in the setter.