28. Bank Account with Validation
Difficulty: Easy · Topic: OOP & classes
Write a class BankAccount(owner, balance=0) and an exception InsufficientFunds (a subclass of Exception):
deposit(amount)andwithdraw(amount)change the balance. An amount that is not positive raisesValueError; so does a negative opening balance.- Withdrawing more than the balance raises
InsufficientFundsand leaves the balance unchanged. balancecan be read but not assigned:acc.balance = 5raisesAttributeError.historyis a list of(kind, amount)tuples for the successful operations, oldest first.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
acc = BankAccount('Asha', 100)
acc.deposit(50)
acc.withdraw(30)
(acc.balance, acc.history)Expected: (120, [('deposit', 50), ('withdraw', 30)])
Hints
Hint 1
Keep the real value inself._balance and expose it with @property; a property with no setter cannot be assigned.Hint 2
Validate first, then change state, so a failed call leaves nothing half-done.Hint 3
class InsufficientFunds(Exception): pass is a complete exception class.Learn the concepts
- Classes, properties and dataclasses · 4 min read. Invariants, validated and read-only attributes, alternate constructors and record types.
- Exceptions and context managers · 5 min read. try/except/else/finally, custom exceptions, with blocks, contextlib and logging.
More Python problems
- Temperature with Properties · Easy
- Build Records from CSV Rows · Medium
- An Abstract Connector Class · Medium
- A Comparable Version Class · Medium
- LRU Cache · Hard
- A Transaction Context Manager · Hard