A small credit union keeps one account per member. Every account has an owner, a balance in whole euros and a history of what happened to it. Write a class Account:
Account(owner, balance=0)opens an account. Its history starts with the entry("open", balance, balance).deposit(amount)addsamountand returns the new balance. Anamountthat is not positive raisesValueErrorand changes nothing.withdraw(amount)takesamountout and returnsTrue, or returnsFalseand changes nothing if the balance is too small. A non-positiveamountraisesValueError.transfer_to(other, amount)moves money to the accountother, with the same rules aswithdraw, and returnsTrueorFalse.history()returns a new list of the entries so far, oldest first.- The attributes
ownerandbalancecan be read directly.
Every change that succeeds adds one entry (kind, amount, balance_after) to the history of each account it touches: the kinds are "deposit", "withdraw", "transfer out" and "transfer in". Refused withdrawals and transfers leave no entry. A transfer from an account to itself follows the same rules: it adds a "transfer out" entry and then a "transfer in" entry to that account, and the balance ends where it started.
The tests run a whole day at the bank with the helper bank_day(Account, script). Each step of the script is a tuple: ("open", name, balance), ("deposit", name, amount), ("withdraw", name, amount), ("transfer", from_name, to_name, amount), ("balance", name) or ("history", name). It returns one result per step (None for "open", and the name of the exception if a method raises one). You can call it with Run. A second helper, history_after_tamper(Account), opens an account with 5 euros, empties the list that its history() returned, and returns a fresh history(); one test uses it to check that the account's past cannot be rewritten from outside.
Examples
Input: bank_day(Account, [("open", "ada", 50), ("open", "bo", 0),
("deposit", "ada", 20), ("withdraw", "bo", 5),
("transfer", "ada", "bo", 30), ("history", "bo")])
Output: [None, None, 70, False, True,
[("open", 0, 0), ("transfer in", 30, 30)]]
Input: bank_day(Account, [("open", "cy", 10), ("deposit", "cy", 0), ("balance", "cy")])
Output: [None, "ValueError", 10]
Constraints
- Amounts and balances are whole numbers; up to
2000steps and50accounts per day. - Changing one account never changes another, except through
transfer_to.
Goals
- Write a class whose objects each keep their own attributes
- Keep a balance and a history consistent by changing them only inside methods
- Avoid the class-level list that every object would share