Python encapsulation and properties
Encapsulation groups state with operations that maintain its rules. This account stores nonnegative integer units and rejects nonpositive deposits.
Python
class Account:
def __init__(self):
self._balance = 0
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self._balance += amount
account = Account()
account.deposit(25)
print(account.balance)
try:
account.deposit(0)
except ValueError:
print("Rejected")
assert account.balance == 25