Project: A Safe Bank Account
Time to combine everything: __init__, methods, a @property, and raising an exception to enforce a rule. You will build a small BankAccount that refuses to go into the red.
Recall how to raise an error when an input is invalid:
def withdraw(amount):
if amount > 100:
raise ValueError("not enough funds")And how a property exposes a computed or guarded value as a plain attribute:
@property
def balance(self):
return self._balanceYour account will track a running balance privately in self._balance, expose it read-only through a balance property, and reject any withdrawal that would overdraw the account by raising ValueError. This is the pattern real systems use: the data is protected, and the rules live with the object that owns the data.
Build a class BankAccount. Its __init__ takes an optional start (default 0) and stores it in self._balance. Add deposit(self, amount) that adds to the balance. Add withdraw(self, amount) that subtracts from the balance, but if amount is greater than the current balance it must raise ValueError and leave the balance unchanged. Expose the balance through a read-only balance @property (no setter).
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.