Bank Account
Write a class BankAccount(owner, balance=0) with:
deposit(amount)andwithdraw(amount); both raiseValueErrorifamountis not greater than zero, andwithdrawalso raisesValueErrorif the balance is too low (the balance must not change).- a read-only property
balance: assigning to it must raiseAttributeError. - an attribute
history: a list of(kind, amount)tuples, such as("deposit", 50), in order. Failed operations are not recorded.
Understand the problem
Look at properties.
What does @property on a method balance do?
- Makes the method run once
- Lets you read
account.balancelike an attribute, while the value is computed by the method - Makes the value constant
A property looks like an attribute from the outside. With only a getter (no setter) it is read-only: assigning to it raises AttributeError. The real value is kept in a private attribute such as _balance.
Why validate before changing the balance in withdraw?
- To make it faster
- So that a failed call leaves the account unchanged
- Because Python requires it
If you subtract first and check afterwards, an error leaves the object in a broken state. Check first, change only when everything is valid. This keeps the object consistent: it never exists half-changed.
Write the solution
Write the whole class.
class BankAccount:
# Write your code here.
pass
Hint 1: a question to ask yourself
Where is the real balance stored, and how do you expose it without letting outsiders assign to it?
Hint 2: the shape of the answer
Store self._balance. Add @property def balance(self): return self._balance with no setter. In deposit and withdraw, validate, then change _balance, then append to history.
Reflect
Solution
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance
self.history = []
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self._balance += amount
self.history.append(("deposit", amount))
def withdraw(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > self._balance:
raise ValueError("insufficient funds")
self._balance -= amount
self.history.append(("withdraw", amount))
What this tests: @property, the underscore convention for internal attributes, input validation, exceptions, and keeping an object consistent.
Encapsulation in Python: nothing is truly private. A leading underscore (_balance) says "internal, please do not touch". A property without a setter makes the public name read-only. That is the Python way: convention plus properties, not private keywords.
Why a property and not a method get_balance(): you can start with a plain attribute and later turn it into a property without changing any code that uses it. Python code does not need getters and setters up front.
Money as numbers: this exercise uses plain numbers. A real system would use integers of cents or Decimal.
What an interviewer might ask next: Add a custom exception InsufficientFunds(ValueError) that carries the missing amount. (See the Errors chapter.)
VISIBLE = 3
CASES = [
('a = BankAccount("Ann", 100)\na.deposit(50)\nresult = a.balance', 150, 'a deposit'),
('a = BankAccount("Ann", 100)\na.withdraw(30)\nresult = a.balance', 70, 'a withdrawal'),
('a = BankAccount("Ann")\nresult = a.balance', 0, 'the default balance'),
('a = BankAccount("Ann", 10)\nresult = error_of(a.withdraw, 20)', 'ValueError', 'too much money'),
('a = BankAccount("Ann", 10)\nerror_of(a.withdraw, 20)\nresult = (a.balance, a.history)', (10, []), 'a failed withdrawal changes nothing'),
('a = BankAccount("Ann", 10)\ntry:\n a.balance = 999\n result = "allowed"\nexcept AttributeError:\n result = "blocked"', 'blocked', 'the balance is read-only'),
('a = BankAccount("Ann")\nresult = (error_of(a.deposit, 0), error_of(a.deposit, -5), error_of(a.withdraw, 0))', ('ValueError', 'ValueError', 'ValueError'), 'amounts must be positive'),
('a = BankAccount("Ann", 100)\na.deposit(50)\na.withdraw(20)\nresult = a.history', [('deposit', 50), ('withdraw', 20)], 'the history'),
('a = BankAccount("Ann")\nb = BankAccount("Bob")\na.deposit(5)\nresult = (b.balance, b.history, a.owner)', (0, [], 'Ann'), 'accounts are independent'),
]