使用*args和**kwargs与Python中的特殊参数。

huangapple go评论68阅读模式
英文:

Using *args and **kwargs with special parameter in Python

问题

Reading the official document, I learned that I can use two special symbols / and * to specify positional and keyword arguments range.

When a function needs to receive variable arguments (*args), you can define it like this:

def function_args_s1(p1, p2, /, pk1, pk2, *, k1, k2, **kwargs):
    pass

Keyword variable arguments (**kwargs) work as expected.

but variable arguments (*args) encounter some errors.

def function_args_s2(p1, p2, *args, /, pk1, pk2, *, k1, k2):
    pass

SyntaxError: invalid syntax
def function_args_s3(p1, p2, /, pk1, pk2, *args, k1, k2):
    pass

pk1 and pk2 are no longer used as keyword parameters because they appear before *args.

<details>
<summary>英文:</summary>

Reading the [offical document](https://docs.python.org/3/tutorial/controlflow.html#special-parameters), I learned that I can use two special symbol `/` and `*` to specify positional and keyword arguments range.

When function need to receive variable `arguments(*args)`, how to define this function?

keyword variable `arguments(**kwargs)` works as expected.

```python
def function_args_s1(p1, p2, /, pk1, pk2, *, k1, k2, **kwargs):
    pass

function_args_s1(1, 2, 1, pk2=2, k1=1, k2=2, k3=3, k4=4)

but variable arguments(*args) meet some error.

def function_args_s2(p1, p2, *args, /, pk1, pk2, *, k1, k2):
    pass

SyntaxError: invalid syntax
def function_args_s3(p1, p2, /, pk1, pk2, *args, k1, k2):
    pass

pk1 and pk2 are no longer use keyword parameter because they before *args

答案1

得分: 1

*args参数在函数中捕获所有剩余的位置参数,这意味着它也执行了*的功能。

def function_args_s2(p1, p2, /, pk1, pk2, *args, k1, k2, **kwargs):
    print(args)
    print(kwargs)

然后

function_args_s2(1, 2, 3, 4, k1=5, k2=6)
()
{}
function_args_s2(1, 2, 3, 4, 5, 6, k1=7, k2=8, kw1=9, kw2=10)
(5, 6)
{'kw1': 9, 'kw2': 10}
英文:

The *args argument in a function is capturing all remaining positional argument, which means it also does what * does.

def function_args_s2(p1, p2, /, pk1, pk2, *args, k1, k2, **kwargs):
    print(args)
    print(kwargs)

Then

function_args_s2(1, 2, 3, 4, k1=5, k2=6)
()
{}
function_args_s2(1, 2, 3, 4, 5, 6, k1=7, k2=8, kw1=9, kw2=10)
(5, 6)
{&#39;kw1&#39;: 9, &#39;kw2&#39;: 10}

答案2

得分: -1

不要在相同的签名中同时使用 *args/*args 允许多个参数,/ 不允许。

英文:

Do not have *args and / in the same signature. *args allows for multiple arguments, / does not.

huangapple
  • 本文由 发表于 2023年6月29日 16:27:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定