Mar-10-2022, 05:44 AM
(This post was last modified: Mar-10-2022, 06:15 PM by deanhystad.)
As Yoriz shows, your class shouldn't just be a collection of functions. Classes should have both variable and method attributes. It is reasonable that the account balance should be an attribute of account. Withdrawals and deposits change the balance. I disagree slightly with Yoriz' in implementation. I would not have a withdrawal or deposit return a balance. And I would write a repr to aid in debugging and testing.
class BankAccount: def __init__(self, first_name, last_name, balance=0.00): self.first_name = first_name self.last_name = last_name self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount > self.balance: raise ValueError( "Transaction declined. Insufficient funds. Deposit some money first." ) self.balance -= amount def __repr__(self): """Return a string that represents the account.""" return f"{self.__class__.__name__}({self.last_name}, {self.first_name}, balance={self.balance})" account = BankAccount("John", "Smith", 100.00) print(account) account.deposit(25) print(account) account.withdraw(75) print(account) account.withdraw(60)
Output:BankAccount(Smith, John, balance=100.0)
BankAccount(Smith, John, balance=125.0)
BankAccount(Smith, John, balance=50.0)
Error:Traceback (most recent call last):
File "...", line 27, in <module>
account.withdraw(60)
File "...", line 12, in withdraw
raise ValueError(
ValueError: Transaction declined. Insufficient funds. Deposit some money first.
I noticed something odd in your code. You do deposits like this:balance = starting_balance + amountBut for a withdrawal you do this:
try: balance = balance - amountIs this not understanding how to raise an exception for a negative balance, or are you protecting against amount not being a number? If the latter, shouldn't you do the same for deposits?