【问题标题】:Is there a way to provide to a function more arguments than it needs?有没有办法为函数提供比它需要的更多的参数?
【发布时间】:2022-11-17 16:37:02
【问题描述】:

我想用 kwargs 将同一个字典的元素传递给几个函数。问题是这个字典包含的函数比参数列表中接收到的函数多。

例如,假设我有以下字典:

d = dict(a=1,b=2,c=3)

现在,我将在接收 dict 中的参数的函数中使用它 - 它会起作用:

def func1(a=3,b=2,c=5):
    return a+b+c

x = func1(**d)

但是,如果函数接收的参数比字典少,它会理所当然地导致错误:

def func2(a=1,b=1):
    return a+b
x = func2(**d)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [4], line 4
      1 def func2(a=1,b=1):
      2     return a+b
----> 4 x = func2(**d)

TypeError: func2() got an unexpected keyword argument 'c'```

有没有办法让这个场景起作用,而不必重新安排我的函数参数?也许通过创建字典的一个子集?有没有一种简短而优雅的方法可以使字典适合函数?

【问题讨论】:

  • 为什么不直接传递对字典的引用而不是将其解包。然后每个函数都可以提取它需要的键/值。可选地, def func2(a=1,b=2,**_)

标签: python dictionary keyword-argument


【解决方案1】:

您可以联系我们*args**kwargs

只需定义您的功能

def func(a, b, **kwargs):
    return a+b

它应该工作。虽然可能是一个快速而肮脏的解决方案...... :-)

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2018-08-19
    • 2023-03-31
    相关资源
    最近更新 更多