简体   繁体   中英

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). How can I use **kwards in the example? 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.

Here's a working version. Also notice the missing comma in func call arguments.

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 :

Did you maybe mean:

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

Notice the missing , ; and then **kwargs should this be: *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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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