简体   繁体   English

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

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

The title seems complicated but the problem itself is easy to describe with an example:标题看起来很复杂,但问题本身很容易用一个例子来描述:

func has another function as a parameter (either my_func1 or my_func2) and I need to provide the parameters to these two function but my_func1 needs three parameters (a,b and c) and my_func2 needs two parameters (a and b). func 有另一个函数作为参数(my_func1 或 my_func2),我需要为这两个函数提供参数,但 my_func1 需要三个参数(a、b 和 c),而 my_func2 需要两个参数(a 和 b)。 How can I use **kwards in the example?如何在示例中使用 **kwards? Many thanks!!非常感谢!!

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

I am not sure what you're trying to achieve here, but you should use *args instead of *kwargs since your parameters aren't named.我不确定你想在这里实现什么,但你应该使用 *args 而不是 *kwargs 因为你的参数没有命名。

Here's a working version.这是一个工作版本。 Also notice the missing comma in func call arguments.还要注意 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)

Looks like a few problems with syntax, for your test :对于您的test ,语法似乎存在一些问题:

Did you maybe mean:您可能是说:

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

Notice the missing , ;注意缺少的, ; and then **kwargs should this be: *args ?然后**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