Python 执行子函数的主函数

Python 执行子函数的主函数,python,function,keyword-argument,Python,Function,Keyword Argument,我有两个接受不同参数的函数: def foo(name, age): pass def bar(color, shape): pass 现在,我有一个主函数,我想用我想执行的函数和它的参数调用它。由于它是一个可以调用foo或bar的主函数,因此只使用两个参数(要执行的函数和此函数的参数)调用它 函数是一个字符串,告诉要执行的函数 params将是一个参数字典(如**kwargs) 我可以这样做以使其工作: def master(function, params): if

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

def foo(name, age):
    pass
def bar(color, shape):
    pass
现在,我有一个主函数,我想用我想执行的函数和它的参数调用它。由于它是一个可以调用foo或bar的主函数,因此只使用两个参数(要执行的函数和此函数的参数)调用它

函数是一个字符串,告诉要执行的函数

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

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

def master(function, params):
    if function == 'foo':
        foo(params['name'], params['age'])
    elif function == 'bar':
        foo(params['color'], params['shape'])
然后我给主人打电话,比如:

master('foo',{'name': 'John', 'age': 99})
然而,如果master有很多子函数要调用,那么就会有太多的条件,并为每个函数选择正确的参数

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

1) 我是否可以直接传递要执行的函数,而不是使用函数名调用master,然后在条件中检查该名称?如果是这样,我该如何执行该函数呢

类似于这样调用master:

master(foo(), {'name': 'John', 'age': 99})
2) 函数
foo
bar
没有**kwarg,但是如果我可以调用它们,只传递一个字典,然后它们从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
所以最后我对大师的理想召唤是:

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

master(foo(), params) # to execute foo
master(bar(), params) # to execute bar

python中的函数是对象,所以可以将它们作为参数传递(但不要使用括号)

然后你叫主人:

master(foo, name='John', age=99...)

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

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)
def master(func, arguments: list):
    return func(*arguments)
如果您不知道函数参数的名称,则可以更简单地执行此操作:

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)
def master(func, arguments: list):
    return func(*arguments)
更通用的版本如下所示:

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

您可以通过master函数执行函数,方法不是将函数作为参数传递到master中,而是传递函数的定义。请遵循以下示例:

   def foo(name, age):
      pass

   def bar(color, shape):
      pass

现在考虑一个主函数:

Func param将通过在函数名后添加括号来包含函数的定义,它将使函数得以执行

def masterFunc(func, params):
     return func(params)  #  Func param will contain the defination of the function by adding parentheses after function name, it will make it to execute. 
您将使用此主函数执行传递的函数定义,如下所示:

masterFunc(foo,{a:1}) #Sample execution

在Python中,函数是对象,与其他任何东西一样。您可以将函数作为参数传递,并非常简单地执行它们

就你而言

 def say_hello(name):
   print "hi ", name

 def say_bye(name, time):
   print name, ", have a good ", time

 say_bye("john", "night")
 john , have a good  night

 def master(fun, **kwargs):
   fun(**kwargs)

 master(say_bye, name='john', time='night')
 john , have a good  night

 params1 = {'name': 'jay', 'time': 'morning'}
 params2 = {'name': 'cole'}

 master(say_hello, **params2)
 hi  cole

 master(say_bye, **params1)
 jay , have a good  morning
这应该是可行的。

函数是Python中的一类对象,因此可以分配给标识符、作为参数传递或由函数返回

您不想为特定函数使用关键字args的统一方式-使用
inspect.getfullargspec
功能:

import inspect

def foo(name, age):
    print(name, age)

def bar(color, shape):
    print(color, shape)

def master(func, params):
    arg_names = inspect.getfullargspec(func).args
    func(**{k:v for k,v in params.items() if k in arg_names})

params = {'name':'John', 'age':99, 'color':'red', 'shape':'circle'}
master(foo, params)
master(bar, params)
样本输出:

John 99
red circle

您可以尝试以下方法

代码
A类:
def a(自身、*args、**kwargs):
打印('A')
def b(自身、*args、**kwargs):
打印('B',args,kwargs)
def主(函数、*args、**kwargs):
x=A()
如果hasattr(x,func):
func=getattr(x,func)
func(*args,**kwargs)
其他:
print('class'.format(func))下未定义函数名{})
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
func=原始输入('func\u名称:a/b')
main(func,(1),{1:1})
输出
~/del$python test.py
职能名称:a/ba
真的
A.
~/del$python test.py
职能名称:a/bb
真的
('B',(1,{1:1}),{})
~/del$
在这里,我们使用
\uuuuu内置的
中的
getattr
函数
*首先,它检查在
class a
的实例下是否有名为
a
b
的函数/方法。 *如果是,则只有它将
getattr
,并执行传递args和kwargs。 *如果有人传递未定义的函数名,它将不会崩溃并返回所需的语句


希望这有帮助

很好的回答!!只需注意,传递主func时不会使用不存在或不在作用域中的func名称。