不识别使用 **kwarg 格式的任意关键字位置参数

Not recognising arbitrary keyword positional arguments using **kwarg format

我正在尝试使用 **kwarg 格式实现一个具有 2 个参数和附加的第三个任意关键字参数的函数,如下所示:

def build_profile(first_name, last_name, **additional_info):
    """ Building a user profile """
    profile = {}
    profile['First name'] = first_name
    profile['Last name'] = last_name
    for key, value in additional_info.items():
        profile[key.title()] = value.title()
    return profile

build_profile("x", 'y', 'x', 'y', 'x', 'y')

但是,这会产生错误:

TypeError: build_profile() takes 2 positional arguments but 6 were given

我设法使用以下代码单独重现此错误:

def x(**y):
    print(y)

输出:

x(1,2,3,4,5)

这会生成相同的响应:

TypeError: x() takes 0 positional arguments but 1 was given

这让我得出结论:

  1. 我的 python 配置有问题(Spyder 中的 运行 3.6.4)或
  2. 我遗漏了一些非常明显的东西。

函数签名中的**kwargs语法用于接受任意数量的关键字参数,即像f(name=value)一样传入的参数。

def f(**kwargs):
    # kwargs is a dict here

用于接受任意数量的 positional 参数的语法看起来像 *args:

def f(*args):
    # args is a tuple here

*** 构成了语法,这种名称选择只是一种约定 - 如果需要,您可以使用其他名称。您也可以同时指定两者。

def f(*splat, **splattysplat):
    ...

如果您想要简约、易于理解的方法,请参考以下示例。

>>> def x(*args):
...    for arg in args:
...        print(arg)

>>> x(1, 2, 3)
1
2
3

>>> def x(**kwargs):
...    for k, v in kwargs.items():
...        print(k, v)

>>> x(name='john', surname='wick')
name john
surname wick