Python Forum
ATM machine (deposits/withdrawals) using OOP
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ATM machine (deposits/withdrawals) using OOP
#4
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 + amount
But for a withdrawal you do this:
       try:
           balance = balance - amount
Is 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?
Drone4four likes this post
Reply


Messages In This Thread
RE: ATM machine (deposits/withdrawals) using OOP - by deanhystad - Mar-10-2022, 05:44 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020