如何从字典中正确调用函数名?

时间:2015-11-06 06:03:01

标签: python python-3.x switch-statement

我正在编写一个ATM程序来练习OO设计,我正在创建一个基于文本的界面来构建GUI原型。作为我的计划的一部分,我有一个main_menu功能,一旦他们验证了他们的信息,就会在账户上提供各种选项。我正在阅读开关/案例陈述,以及他们在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()

2 个答案:

答案 0 :(得分:1)

替换

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这样的dict中的所有值都必须是文件中定义的模块级函数。

答案 1 :(得分:1)

您可以尝试getattr(obj, attr)。在您的代码中,转移

func = 'self.atm.' + functions.get(user_in)

func = getattr(self.atm, functions.get(user_in))