2009-04-23 43 views
0

我想写一点代码来调用给定参数指定的函数。 EG:实现'函数调用函数'

def caller(func): 
    return func() 

不过我还要做的是指定的可选参数“主叫方”功能,使“来电显示”呼叫“功能”与指定的参数(如果有的话)。

def caller(func, args): 
# calls func with the arguments specified in args 

有没有简单的pythonic方法来做到这一点?

+0

这是scarily元。你确定你没有过度泛化吗? – 2009-04-23 16:53:35

回答

12

您可以通过使用arbitrary argument listsunpacking argument lists来完成此操作。

>>> def caller(func, *args, **kwargs): 
...  return func(*args, **kwargs) 
... 
>>> def hello(a, b, c): 
...  print a, b, c 
... 
>>> caller(hello, 1, b=5, c=7) 
1 5 7 

不知道为什么觉得有必要去做,虽然。

7

这已经作为apply函数存在,尽管由于新的* args和** kwargs语法而被认为是过时的。

>>> def foo(a,b,c): print a,b,c 
>>> apply(foo, (1,2,3)) 
1 2 3 
>>> apply(foo, (1,2), {'c':3}) # also accepts keyword args 

但是,*和**语法通常是更好的解决方案。以上相当于:

>>> foo(*(1,2), **{'c':3})