Medium: Interview Core · Problem 46 of 82

Bank Account

MediumClassesPython

Write a class BankAccount(owner, balance=0) with:

  • deposit(amount) and withdraw(amount); both raise ValueError if amount is not greater than zero, and withdraw also raises ValueError if the balance is too low (the balance must not change).
  • a read-only property balance: assigning to it must raise AttributeError.
  • 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?

  1. Makes the method run once
  2. Lets you read account.balance like an attribute, while the value is computed by the method
  3. 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?

  1. To make it faster
  2. So that a failed call leaves the account unchanged
  3. 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.)