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

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

问题描述

我正在制作一个程序,它有一个主菜单,要求用户输入一个选项,并将其存储在整数 option1 中,这是在字典选项。然后运行相应的功能。如果函数没有参数,以下代码可以工作:

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.

推荐答案

当然可以。在Python中,函数可以使用位置或关键字参数。对于大多数函数,可以以任意一种方式传递参数,但是并不一定是所有函数都是这样,因此我们需要将它们分开。位置参数是一个可迭代(通常是列表或元组),关键字参数在字符串中的字符串到值。

Sure. In Python, functions can take positional or keyword arguments. For most functions, arguments can be passed in either way, but that’s not necessarily the case for all functions, so we do need to keep them separate. Positional arguments are in an iterable (often list or tuple), and keyword arguments are in a dictionary from strings to values.

然后我们可以将每个函数表示为一个元组函数,位置参数和关键字参数:

We could then represent each function as a tuple of function, positional arguments, and keyword arguments:

options = {
    0: (function_zero, [], {}),
    1: (function_one, [], {}),
    2: (function_two, [], {}),
    3: (function_three, [True], {}),
    4: (function_four, [], {'kwarg': True}),  # takes a keyword argument
}

然后你可以这样调用:

func, args, kwargs = options[option1]
func(*args, **kwargs)

但如果你总是要传递一个常量,有一个更好的方法:只需为调用函数的每个函数创建一个无参数的包装器

But if you’re always going to just pass in a constant, there’s a better way: just create little no-argument wrappers for each function that call the function how you want it to be called:

options = {
    0: function_zero,
    1: function_one,
    2: function_two,
    3: lambda: function_three(True),
    4: lambda: function_four(kwarg=True),
}

然后使用您的第一个方法:

Then use your first method:

options[option1]()

如jonrsharpe的答案所述,您还可以使用 functools.partial 而不是 lambda 。正如他所说,这样做的优点是能够附加一些你自己的论据:

As detailed in jonrsharpe’s answer, you can also use functools.partial rather than a lambda. As he notes, this has the advantage of being able to append some of your own arguments:

options[option1]('hello')  # adds 'hello' to previously-specified arguments

如果不需要此功能,但是,零参数 lambda 将为您服务。

If you don’t need this functionality, though, a zero-parameter lambda will serve you just fine.

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

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