簡體   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