简体   繁体   English

在使用** kwargs时分配* args

[英]Assign *args while using **kwargs

I have a python function which looks like this: 我有一个看起来像这样的python函数:

def test(a, b, *args):
    print(a, b, args)

And I have a dictionary (kwargs) which has only a and b as items in it. 我有一本字典(kwargs),其中只有a和b作为项目。 I would like to call test like this: 我想这样称呼测试:

test(**kwargs)

and assign more values to args . 并为args分配更多值。 How do I do it, and if I can't, What is the right way to do this? 我该怎么做,如果不能,那么正确的方法是什么?

You defined your function to always accept an either positional or keyword arguments: a and b , and a list of positional arguments after that. 您将函数定义为始终接受位置参数或关键字参数: ab ,以及之后的位置参数列表。

In Python it's a Syntax Error to provide a positional argument after a keyword argument. 在Python中,在关键字参数之后提供位置参数是一种语法错误。

Therefore, you cannot use **kwargs dictionary unpacking in your method call, if you also want to provide additional positional arguments. 因此,如果您还想提供其他位置参数,则不能在方法调用中使用**kwargs字典解包。

What you can do, though, is either use positional arguments only - making sure that a and b are the first two elements in your list. 但是,您只能使用位置参数-确保ab是列表中的前两个元素。

Or if you really wan't to use a dictionary, You'd have to directly get a and b values, pass it positionally as a and b , and then get remaining items() from your dictionary and call your function with it. 或者,如果您真的不想使用字典,则必须直接获取ab值,将其作为ab位置传递,然后从字典中获取剩余的items()并使用它来调用函数。 This will lose the key values though. 但是,这将丢失键值。

You can try using just *args as argument. 您可以尝试仅使用*args作为参数。

Ex: 例如:

def test(*args):
    print(args)

test({"a": 1, "b":2, "c":3, "d":[1,2,3,45]})

Output: 输出:

({'a': 1, 'c': 3, 'b': 2, 'd': [1, 2, 3, 45]},)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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