[英]How can I get data for a class object, taking input from user of which object he would like to view?
[英]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.