如何正确调用字典中的函数名?
How to correctly call a function name from a dictionary?
我正在编写一个 ATM 程序来练习 OO 设计,我正在创建一个基于文本的界面来制作 GUI 原型。作为我程序的一部分,我有一个 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 中的相应函数。
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 必须是在您的文件中定义的模块级函数。
你可以试试getattr(obj, attr)
。在你的代码中,transfer
func = 'self.atm.' + functions.get(user_in)
到
func = getattr(self.atm, functions.get(user_in))
我正在编写一个 ATM 程序来练习 OO 设计,我正在创建一个基于文本的界面来制作 GUI 原型。作为我程序的一部分,我有一个 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 中的相应函数。
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 必须是在您的文件中定义的模块级函数。
你可以试试getattr(obj, attr)
。在你的代码中,transfer
func = 'self.atm.' + functions.get(user_in)
到
func = getattr(self.atm, functions.get(user_in))