将函数的所有参数传递给另一个函数

我想将传递给函数(func1)的所有参数作为参数传递给 func1中的另一个函数(func2) 这可以通过 func1中的 *args, *kwargs来完成,并将它们传递给 func2,但是还有其他方法吗?

本来

def func1(*args, **kwargs):
func2(*args, **kwargs)

但是如果我的 fun1签名是

def func1(a=1, b=2, c=3):

如何不使用

def func1(a=1, b=2, c=3):
func2(a, b, c)

有没有像 javascript callee.arguments那样的方法?

49542 次浏览

Explicit is better than implicit but if you really don't want to type a few characters:

def func1(a=1, b=2, c=3):
func2(**locals())

locals() are all local variables, so you can't set any extra vars before calling func2 or they will get passed too.

Provided that the arguments to func1 are only keyword arguments, you could do this:

def func1(a=1, b=2, c=3):
func2(**locals())

As others have said, using locals() might cause you to pass on more variables than intended, if func1() creates new variables before calling func2().

This is can be circumvented by calling locals() as the first thing, like so:

def func1(a=1, b=2,c=3):
par = locals()


d = par["a"] + par["b"]


func2(**par)