我试图在 python 的另一个函数中调用一个函数,但找不到正确的语法。我想做的是这样的:
def wrapper(func, args):
func(args)
def func1(x):
print(x)
def func2(x, y, z):
return x+y+z
wrapper(func1, [x])
wrapper(func2, [x, y, z])
在这种情况下,第一次调用会起作用,第二次不会。 我要修改的是包装函数,而不是调用函数。
最佳答案
稍微扩展其他答案:
行内:
def wrapper(func, *args):
args
旁边的 * 表示“获取给定的其余参数并将它们放入名为 args
的列表中”。
行内:
func(*args)
这里 args
旁边的 * 表示“将这个名为 args 的列表‘解包’到其余参数中。
因此您可以执行以下操作:
def wrapper1(func, *args): # with star
func(*args)
def wrapper2(func, args): # without star
func(*args)
def func2(x, y, z):
print x+y+z
wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])
在 wrapper2
中,列表是显式传递的,但在两个包装器 args
中都包含列表 [1,2,3]
。
https://stackoverflow.com/questions/817087/