BankAccount

Python Morsels Exercise

Class representing a bank account with read-only balance

3 bonuses 7 hints 8 solutions 173 users solved 20 reviews

I'd like you to make a class that represents a bank account.

Your bank account should accept an optional balance argument (defaulting to 0), have a balance attribute, and have deposit, withdraw, and transfer methods:

>>> a1 = BankAccount()
>>> a1.balance
0
>>> a1.deposit(10)
>>> a1.balance
10
>>> a2 = BankAccount(balance=20)
>>> a2.withdraw(15)
>>> a2.balance
5
>>> a1.transfer(a2, 3)
>>> a1
BankAccount(balance=7)
>>> a2
BankAccount(balance=8)

Your bank account should also have a nice string representation (as shown above).

This example might not seem realistic (it's not) but it's a classic example for good reason:

  1. most real-world object-oriented programming in Python involves a lot of code (classes aren't usually worth the complexity until you have a sufficiently complex problem)
  2. a bank account is a pretty common and familiar concept which doesn't require a lot of domain-specific knowledge

Bonus 1


This is just a preview of the problem statement.

This exercise includes 3 bonuses and 7 hint links.

To solve this exercise, sign in to your Python Morsels account.

A learning habit for experienced Pythonistas

Profile picture of Trey

My name is Trey Hunner and I hold Python trainings for teams. I've spent countless hours refining my most interesting Python exercises into Python Morsels, a Python skill-building platform for folks who already know Python. Python Morsels is design to help you deepen your Python skills every week.

Sign up for Python Morsels to access this exercise and many more.

Join Python Morsels ✨