简体   繁体   中英

taking input from user to decide which object will be used in python class

i am new here and i am trying to learn python. i want to create a simple atm program but i also want to try something that i haven't seen yet. i want to take input from user and select one of objects of a class regard to this selection, here is the part of my code

class bankaccount():

    def __init__(self,name,money):

        self.name=name
        self.money=money

    def show(self):

        print(self.name,self.money)


johnaccount=bankaccount("john",500)
mikeaccount=bankaccount("mike",1000)
sarahaccount=bankaccount("sarah",1500)

selection= input("please write the name: ")

for example i will write john and program should run johnaccount.show is this possible? could you please help about this issue.

There is a "hacky" way to do that (see below). Usually you'd rather have a dictionary or list containing all of the accounts and then get the account from there.

For example:

accounts = {
  'john': bankaccount("john",500),
  'mike': bankaccount("mike",1000)
}

selection = input("please write the name: ")
if selection in accounts:
  print(f"Balance: {accounts[selection].show()}") 
else:
  print("Account not found")

The "hacky" way is to use Python's built-in locals function:

johnaccount=bankaccount("john",500)
mikeaccount=bankaccount("mike",1000)
sarahaccount=bankaccount("sarah",1500)

selection = input("please write the name: ")
account_name =  f"{selection}account"

if account_name in locals():
  print(f"Balance: {locals()[account_name].show()}") 
else:
  print("Account not found")

The f"Balance: {accounts[selection].show()}" syntax that I'm using is called f-strings , or formatted string literals .

PS. it's common practice to use CamelCase for class names, eg BankAccount , and to use lowercase and underscores for variable names , eg john_account .

Below

class bankaccount():

    def __init__(self,name,money):
        self.name=name
        self.money=money

    def show(self):
        print(self.name,self.money)

# build the accounts 'DB' (which is just a dict)
# read more here: https://cmdlinetips.com/2018/01/5-examples-using-dict-comprehension/
accounts = {name: bankaccount(name,balance) for name,balance in [("john",500),("mike",1000)]}

user = input("please write the name: ")

account = accounts.get(user)
if account:
  account.show()
else:
  print(f'no account for {user}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM