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
Implementation
The account in four parts: birth, questions, actions, and the private rule.
The point: all rules meet in one private method, and questions and actions both use it.
BankAccount, part by part
BankAccount
The constructor is the first gate. After it, the account is valid.
class Refused(Exception): """The account said no. The message says why."""class BankAccount: DAILY_LIMIT = 50_000 def __init__(self, holder: str, number: str) -> None: if not holder.strip(): raise ValueError("holder is required") self._holder = holder.strip() self._number = number self._balance_cents = 0 self._frozen = False self._day = 0 self._taken_today = 0Lines 1 to 2
An own error type. Callers can tell a refusal from a bug. With a bare false they could ignore it without noticing.
1 of 5
Why it is built this way
- The underscore is a convention in Python. In Java, C++ and TypeScript the language stops the caller.
- In Java write
private finalfor holder and number: set once, checked by the compiler.