【问题标题】:python call function with arguments from dictionary带有字典参数的python调用函数
【发布时间】:2017-09-04 08:26:44
【问题描述】:

我在我的脚本中有一个地方,我要求用户提供一些反馈(选择脚本中的下一阶段),并且由于大量的项目用户正在做出决定,我将我的“if-else”部分包装成一个字典。我可以调用任何“普通”函数,但在很多情况下,我必须调用相同的函数但带有一些参数,但无法弄清楚如何将这些添加到我已经拥有的脚本正文中。它看起来像这样(我会尝试对其发表评论,以便您了解我的问题所在):

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()

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

【问题讨论】:

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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    import functools
    options = {
        ...
        '2': functools.partial(fn, arg1, arg2, arg3)
        ...
    }
    

    【讨论】:

    • 不知道,谢谢。我还在学习,而且 functools 甚至不在我的清单上“现在需要知道”:-) 实际上不是比 lambda 解决方案更好吗? (没有导入,更简单的语法)
    猜你喜欢
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2018-08-14
    • 1970-01-01
    相关资源
    最近更新 更多