the*_*rty 0 python functional-programming function
我想编写一些调用给定参数指定的函数的代码.例如:
def caller(func):
    return func()
然而,我还想做的是为'caller'函数指定可选参数,以便'caller'使用指定的参数调用'func'(如果有的话).
def caller(func, args):
# calls func with the arguments specified in args
有一种简单的pythonic方法吗?
Pao*_*ino 12
>>> 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
但不确定为什么你觉得有必要这样做.
这已经作为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})