【问题标题】:How to to pass optional parameters from one function to another function, which is also a parameter of the first function?如何将可选参数从一个函数传递给另一个函数,这也是第一个函数的参数?
【发布时间】:2020-06-14 22:54:00
【问题描述】:

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

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

【问题讨论】:

  • **kwargs 是关键字参数,通常命名为参数(例如使用字典)。您是否尝试过 *args 用于非关键字参数??

标签: python optional-parameters


【解决方案1】:

对于您的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

【讨论】:

    【解决方案2】:

    我不确定您要在这里实现什么,但您应该使用 *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)
    

    【讨论】:

    • 非常感谢!我现在明白 *args 和 **kwards 是如何工作的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2012-09-25
    • 2020-10-03
    相关资源
    最近更新 更多