python调用函数与字典中的参数

时间:2017-04-09 06:30:39

标签: python-3.x function dictionary arguments call

我在我的脚本中有一个位置,我要求用户提供一些反馈(选择脚本中的下一个阶段),并且由于用户正在做大量的项目,我将包裹我的' if-else&# 39;部分成字典。我可以打电话给任何' plain'函数,但在很多情况下我必须调用相同的函数,但有一些参数,但无法弄清楚如何将这些添加到我已经拥有的脚本的主体。它看起来像这样(我会尝试评论它,所以你看到我有问题):

def runthis():

    # getting user input
    decide = input(str(
        'Select option 1'
        'Select option 2'
        'Select option 3'
        'Select option etc'
        'Select option n'))

    # each action listed here as a function without parentesis and arguments
    options = {
        '1': func1,
        '2': func2,
        '3': func3,
        'etc': funcetc,
        'n': funcn}

    # go through the list and look for key matching user decision
    # then run the value as a function - how to pass arguments when I need?
    if decide in options.keys():
        options[decide]()
    else:
        print('invalid entry')
        runthis()


runthis()

谢谢,任何帮助都非常感激。

2 个答案:

答案 0 :(得分:1)

答案很简单 - 对于我需要添加参数的那些我只需将值称为lambda ...就像这样:

# say func 2 holds 3 arguments
options = {
    '1': func1,
    '2': lambda: func2(arg1, arg2, arg3),
    '3': func3,
    'etc': funcetc,
    'n': funcn}

如此简单的解决方案,人们看不到它

答案 1 :(得分:0)

{ "port": 10666, } 模块为您提供了操作函数的方法,包括partial,允许您将参数部分传递给函数,例如:

functools
相关问题