簡體   English   中英

從用戶那里獲取輸入來決定將在 python 類中使用哪個對象

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

我是新來的,我正在嘗試學習 python。 我想創建一個簡單的 atm 程序,但我也想嘗試一些我還沒有見過的東西。 我想從用戶那里獲取輸入並選擇一個關於這個選擇的類的對象,這是我的代碼的一部分

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: ")

例如我會寫 john 並且程序應該運行 johnaccount.show 這可能嗎? 你能幫忙解決這個問題嗎?

有一種“hacky”方式可以做到這一點(見下文)。 通常,您寧願擁有包含所有帳戶的字典列表,然后從那里獲取帳戶。

例如:

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")

“hacky”方法是使用 Python 的內置locals函數:

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")

我使用的f"Balance: {accounts[selection].show()}"語法稱為f-strings ,或格式化字符串文字

附注。 通常的做法是使用 CamelCase 作為類名,例如BankAccount ,並使用小寫和下划線作為變量名,例如john_account

以下

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}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM