Encapsulation
easy 35 minPut the data and the methods that work on it into one unit, and let outside code reach the data only through those methods.
Watch lesson4:51
Problem
A bank account with public fields, and rules that live in three other classes.
The point: find the rules first. Encapsulation means moving them to the class that has the data.
The code we get
Python
class BankAccount: def __init__(self, holder, number): self.holder, self.number, self.balance = holder, number, 0.0def pay_out(account, amount): # in the cash machine if amount <= account.balance: # the limit is missing here account.balance -= amountdef web_transfer(a, b, amount): # in the web shop if 0 < amount <= a.balance: a.balance -= amount b.balance += amountjohn, jane = BankAccount("John", "123456"), BankAccount("Jane", "654321")john.balance = 500.0pay_out(john, -100) # a negative amount prints moneyprint(john.balance)print(0.1 + 0.2 == 0.3) # and float money does not add upWhere each rule lives
| Rule | Today | After |
|---|---|---|
| An amount is positive | web shop only | deposit and withdraw |
| The balance is never below zero | two copies | one private check |
| At most 500.00 a day | nowhere | same private check |
| A frozen account pays nothing | nowhere | same private check |
| Money is exact | float | whole cents |
| The full number is not shown | every page decides | masked_number |