执行子功能的主功能

Sem*_*aki 2 python function kwargs

我有两个接受不同参数的函数:

def foo(name, age):
    pass
def bar(color, shape):
    pass
Run Code Online (Sandbox Code Playgroud)

现在,我有一个主函数,我希望能够使用我要执行的函数及其参数进行调用。由于它是一个可以调用foo或bar的主函数,因此仅使用两个参数(要执行的函数和该函数的参数)进行调用。

function是一个字符串,告诉执行什么功能

params将是参数字典(例如** kwargs)

我可以这样做以使其工作:

def master(function, params):
    if function == 'foo':
        foo(params['name'], params['age'])
    elif function == 'bar':
        foo(params['color'], params['shape'])
Run Code Online (Sandbox Code Playgroud)

然后我打电话给师父:

master('foo',{'name': 'John', 'age': 99})
Run Code Online (Sandbox Code Playgroud)

但是,如果master需要调用许多子功能,则条件太多,无法为每个函数选择正确的参数。

所以我基本上有两个问题:

1)我可以直接传递要执行的功能,而不是用功能名称调用master,然后在某种情况下检查该名称吗?如果是这样,我该如何执行该功能?

像这样打电话给主人:

master(foo(), {'name': 'John', 'age': 99})
Run Code Online (Sandbox Code Playgroud)

2)函数foo并且bar没有** kwargs,但是如果我可以仅通过字典调用它们,然后将它们从dict赋给每个变量的值,那将非常方便。

所以基本上,我可以这样做:

params = {'name':'John', 'age':99, 'color':red, 'shape':circle}
foo(params)  # I would like to to this even if foo doesn't have **kwargs
bar(params)  # same for bar
Run Code Online (Sandbox Code Playgroud)

因此,最后,我理想的主人呼吁是:

params = {'name':'John', 'age':99, 'color':red, 'shape':circle}

master(foo(), params) # to execute foo
master(bar(), params) # to execute bar
Run Code Online (Sandbox Code Playgroud)

For*_*Bru 5

您可以将函数作为参数传递:

def master(func, arguments: dict):
    if func is foo:
        args = arguments["name"], arguments["age"]
    elif func is bar:
        args = arguments["color"], arguments["shape"]

    return func(*args)
Run Code Online (Sandbox Code Playgroud)

如果您不知道函数参数的名称,则可以更简单地完成此操作:

def master(func, arguments: list):
    return func(*arguments)
Run Code Online (Sandbox Code Playgroud)

以下是更为通用的版本:

def master(function, *positional_arguments, **keyword_arguments):
    function(*positional_arguments, **keyword_arguments)

master(foo, 'John', 56)
master(foo, **{'name': 'John', 'age': 56})
master(foo, name='John', age=56)
master(foo, *['John', 56])
Run Code Online (Sandbox Code Playgroud)