在 Python 中使用字典调用带参数的函数 [英] Calling functions with parameters using a dictionary in Python

查看:63
本文介绍了在 Python 中使用字典调用带参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个程序,它有一个主菜单,要求用户输入一个选项并将其存储在整数 option1 中,该整数在字典 options 中查找.然后运行相应的函数.如果函数没有参数,以下代码有效:

I'm making a program which has a main menu that asks the user to input an option and store it in integer option1, which is looked up in dictionary options. The corresponding function is then run. The following code works if the functions have no parameters:

options = {0 : FunctionZero,    # Assign functions to the dictionary
            1 : FunctionOne,
            2 : FunctionTwo,
            3 : FunctionThree}

options[option1]()    # Call the function

如果函数有参数,上面的代码不起作用,因为 () 部分假设函数没有参数,但我尝试了以下方法,它将函数的名称和参数存储在元组中字典内:

If the functions have parameters the above code doesn't work as the () part assumes the functions have no parameters, but I tried the following, which stores the functions' names and parameters in tuples within the dictionary:

options = {0 : (FunctionZero,""),    # FunctionsZero, FunctionOne
            1 : (FunctionOne,""),    # and FunctionTwo have no parameters
            2 : (FunctionTwo,""),
            3 : (FunctionThree,True)}    # FunctionThree has one parameter

if options[option1][1] == "":    # Call the function
    options[option1][0]()
else:
    options[option1][0](options[option1][1])

这段代码似乎工作正常,但我想知道是否有更好的方法来做到这一点,尤其是在函数需要多个参数的情况下?在 C# 等其他语言中,我可能会使用 switch 或 case 语句(Python 中没有),并且我避免为此使用 if...elif 语句.

This code seems to work fine, but I was wondering if there's a better way to do this, especially if the functions require several parameters? In other languages like C# I'd probably use a switch or case statement (which is not in Python) and I'm avoiding using if...elif statements for this.

推荐答案

我会使用 functools.partial 指定创建字典时的参数:

I would do this using functools.partial to specify the arguments when the dictionary is created:

from functools import partial

options = {0: FunctionZero,   
           1: FunctionOne,    
           2: FunctionTwo,
           3: partial(FunctionThree, True)} 

注意这也允许在调用函数时传递额外的参数(只要字典中的所有函数在partial被调用后都缺少相同的参数):

Note that this also allows additional parameters to be passed when the function is called (as long as all the functions in the dictionary have the same parameters missing after partial has been called):

def test(one, two, three=None, four=None):
    ...

def test2(one, two, three=None):
    ...

options = {1: partial(test, 1, three=3, four=4),
           2: partial(test2, 1, three=3)}

...

options[choice](2) # pass the 'two' argument both functions still require

这篇关于在 Python 中使用字典调用带参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆