繁体   English   中英

如何将可选参数从一个函数传递给另一个函数,另一个函数也是第一个函数的参数?

[英]How to to pass optional parameters from one function to another function, which is also a parameter of the first function?

标题看起来很复杂,但问题本身很容易用一个例子来描述:

func 有另一个函数作为参数(my_func1 或 my_func2),我需要为这两个函数提供参数,但 my_func1 需要三个参数(a、b 和 c),而 my_func2 需要两个参数(a 和 b)。 如何在示例中使用 **kwards? 非常感谢!!

def my_func1(a,b,c):
    result = a + b + c
    return result
def my_func2(a,b):
    resultado = a*b
    return resultado
def func(function,a,**kwargs):
    z = function(a,**kwargs)
    return z
test = func(my_func1,3,3 3)
ERROR:
ile "<ipython-input-308-ada7f9588361>", line 1
    prueba = func(my_func1,3,3 3)
                               ^
SyntaxError: invalid syntax

我不确定你想在这里实现什么,但你应该使用 *args 而不是 *kwargs 因为你的参数没有命名。

这是一个工作版本。 还要注意 func 调用参数中缺少的逗号。

def my_func1(a,b,c):
    result = a + b + c
    return result

def my_func2(a,b):
    resultado = a*b
    return resultado

def func(function,a,*args):
    z = function(a,*args)
    return z

test = func(my_func1,3,3, 3)
print(test)

对于您的test ,语法似乎存在一些问题:

您可能是说:

test = func(my_func1,3,3, 3)

注意缺少的, ; 然后**kwargs应该是: *args吗?

def my_func1(a,b,c):
    result = a + b + c
    return result

def my_func2(a,b):
    resultado = a*b
    return resultado

def func(function,*args):
    z = function(*args)
    return z

print(func(my_func2,3,3)); # prints 9
print(func(my_func1,3,3,3)); # prints 9

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM