0

I´m working on a small project to get some exercise in OOP, which should be a kind of Bank-Simulator.

How do i change the object to use a method on without checking each variant with if clauses? To example, how do I input the person to use display on based on the input without checking each person with an if clause?

class Bank:
  def __init__(self, name, balance):
    self.name = name
    self.balance = balance

  def transfer(self, recipient):
    amount = float(input('What amount do you want to transfer? \n'))
    if amount >= self.balance:
      self.balance -= amount
      recipient.balance += amount
    else:
      print('Your balance does not cover that transfer!')

  def display(self):
    print('Your balance is: ')
    print(self.balance)

person_one = Bank('Steve', 1000)
person_two = Bank('Bob', 1000)

while True:
  User = input('What is your name?')
  print('Which action would you like to take?')
  action = input('Your choices are display, deposit and withdraw \n')
  if action in ('display', 'deposit', 'withdraw'):
    if action == 'display':
      User.display()

  • I do not understand your problem. Please provide an example of output you are expecting (if applicable). – Itération 122442 Aug 16 '23 at 06:27
  • Does this answer your question? [In Python, when to use a Dictionary, List or Set?](https://stackoverflow.com/questions/3489071/in-python-when-to-use-a-dictionary-list-or-set) Tl;DR you want to use a dictionary if you want a mapping between names and objects. If you want different ways to search for a user you might want to go with lists as well – Abdul Aziz Barkat Aug 16 '23 at 06:46

2 Answers2

2

The good option is to use a dictionary as a database where each key is a user (customer) and the associated value is an instance of Bank.

Something like this:

class Bank:
    def __init__(self, name: str, balance: float):
        self._name = name
        self._balance = balance
    def deposit(self, amount: float):
        self._balance += amount
    def withdraw(self, amount: float):
        self._balance -= amount
    def __str__(self):
        return f'{self._name} {self._balance:.2f}'

database = {}

print('Database creation ----->')
while name := input('Enter a name or <return> to end: '):
    amount = float(input('Enter an initial balance: '))
    database[name] = Bank(name, amount)

print('Database access ----->')
while name := input('Enter a name or <return> to end: '):
    if (account := database.get(name)):
        match input('What would you like to do? display, deposit or withdraw? '):
            case 'display':
                print(account)
            case 'deposit':
                amount = float(input('Enter deposit amount: '))
                account.deposit(amount)
            case 'withdraw':
                amount = float(input('Enter withdrawal amount: '))
                account.withdraw(amount)
            case _:
                print('Invalid action')
    else:
        print(f'{name} not in database')

Usage example:

Database creation ----->
Enter a name or <return> to end: Bill
Enter an initial balance: 100
Enter a name or <return> to end: Dave
Enter an initial balance: 200
Enter a name or <return> to end: 
Database access ----->
Enter a name or <return> to end: Bill
What would you like to do? display, deposit or withdraw? display
Bill 100.00
Enter a name or <return> to end: chris
chris not in database
Enter a name or <return> to end: Dave
What would you like to do? display, deposit or withdraw? deposit
Enter deposit amount: 50
Enter a name or <return> to end: Dave
What would you like to do? display, deposit or withdraw? display
Dave 250.00
Enter a name or <return> to end:
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • Hi @DarkKnight, this looks awesome! Just as a question as I dont quite understand that point: Why does pressing return end it? – Joshua Hildebrandt Aug 16 '23 at 08:10
  • @JoshuaHildebrandt If you just press return/enter then *input()* will return an empty string (which is falsey) and therefore the *while* loop will break. The code has two loops - one to build the "database" and the other to access it – DarkKnight Aug 16 '23 at 08:16
1

Is this what you are trying to do?

class Bank:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

    def transfer(self, recipient):
        amount = float(input('What amount do you want to transfer?\n'))
        if amount >= self.balance:
            self.balance -= amount
            recipient.balance += amount
        else:
            print('Your balance does not cover that transfer!')

    def display(self):
        print('Your balance is:')
        print(self.balance)

person_one = Bank('Steve', 1000)
person_two = Bank('Bob', 1000)

while True:
    user = input('What is your name?')
    print('Which action would you like to take?')
    action = input('Your choices are display, deposit, and withdraw\n')
    
    actions = {
        'display': Bank.display,
        'deposit': Bank.deposit,  # Add a deposit method to your Bank class
        'withdraw': Bank.withdraw  # Add a withdraw method to your Bank class
    }
    
    if action in actions:
        selected_action = actions[action]
        selected_action(person_one if user == 'Steve' else person_two)
    else:
        print('Invalid action. Please choose display, deposit, or withdraw.')
pr_kr1993
  • 185
  • 6
  • Hi, kind of. I´m trying to make this a bit more scalable, say 10 people, and checking for every person with an if/else clause might be too unhandy for this. Is there a way to ask which customer makes the request( like user) and input that user instead of Bank in Bank.display() ? – Joshua Hildebrandt Aug 16 '23 at 06:39
  • 1
    @JoshuaHildebrandt If you start appending numbers to the names of your variables, it is usually a sign that you are doing something wrong. Use an appropriate data structure, e.g. a list or a dictionary. – Matthias Aug 16 '23 at 06:45