gpt4 book ai didi

python - 如何正确调用字典中的函数名?

转载 作者:行者123 更新时间:2023-12-01 04:22:22 27 4
gpt4 key购买 nike

我正在编写一个 ATM 程序来练习 OO 设计,并且正在创建一个基于文本的界面来构建 GUI 原型(prototype)。作为我的程序的一部分,我有一个 main_menu 函数,一旦他们验证了他们的信息,它就会为帐户提供各种选项。我正在阅读 switch/case 语句,以及它们在 Python 中明显缺失的内容,然后在官方网站 https://docs.python.org/2/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python 上找到了一些公式。关于如何创建类似的效果。这是示例:

def function_1(...):
...

functions = {'a': function_1,
'b': function_2,
'c': self.method_1, ...}

func = functions[value]
func()

我想我已经很接近了,但我收到了字符串不可调用的错误。我的字典中的函数都映射到我的 ATM 类中的相应函数。

class ATMTextInterface(object):

def __init__(self, atm):
self.atm = atm
self.name = ''
self.user_id = ''
self.pin = ''
self._run()

def _get_inputs(self):
self.name = input('Please enter your name: ')
self.user_id = eval(input('Please enter your User ID: '))
self.pin = eval(input("Now enter your pin: "))
return self.name, self.user_id, self.pin

def _initial_screen(self):
user_in = ''
while user_in != 'Q':
print('{:^10}'.format('Welcome to the ATM!\n'))
print('(A)ccess Account')
print('(Q)uit')
user_in = input('Please enter selection: ').upper()

if user_in == 'A':
user_info = self._get_inputs()
if self.atm.access_account(user_info[1], user_info[2]):
print('Information successfully validated.')
break
else:
add_new = input('Information not recognized. '
'Would you like to add a new user? ')
if add_new == 'Y':
self.atm.add_user(*user_info)
elif user_in == 'Q':
continue
else:
print('Selection not recognized, please try again.')

def _main_menu(self):
user_in = ''
functions = {
'1': 'check_balance',
'2': 'make_deposit',
'3': 'make_withdrawal',
'4': 'select_account',
'5': 'transfer_money'
}
while user_in != 'Q':
print('{}{}{}\n'.format('-' * 10, 'MAIN MENU', '-' * 10))
print('Please select one of the following options: \n\n')
options = ['1. Check Balance', '2. Make Deposit',
'3. Make Withdrawal', '4. Select Account',
'5. Transfer Funds', '(Q)uit']
print('\n'.join(options))
user_in = input('>> ') #.upper()
func = 'self.atm.' + functions.get(user_in)
func()

def _run(self):
self._initial_screen()
self._main_menu()

最佳答案

替换

functions = {
'1': 'check_balance',
'2': 'make_deposit',
'3': 'make_withdrawal',
'4': 'select_account',
'5': 'transfer_money'
}

functions = {
'1': check_balance,
'2': make_deposit,
'3': make_withdrawal,
'4': select_account,
'5': transfer_money
}

此外,字典中的所有值(例如 check_balance)必须是在文件中定义的模块级函数。

关于python - 如何正确调用字典中的函数名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560452/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com