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

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

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:

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

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

but variable arguments (*args) encounter some errors.

  1. def function_args_s2(p1, p2, *args, /, pk1, pk2, *, k1, k2):
  2. pass
  3. SyntaxError: invalid syntax
  1. def function_args_s3(p1, p2, /, pk1, pk2, *args, k1, k2):
  2. pass
  3. pk1 and pk2 are no longer used as keyword parameters because they appear before *args.
  4. <details>
  5. <summary>英文:</summary>
  6. 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.
  7. When function need to receive variable `arguments(*args)`, how to define this function?
  8. keyword variable `arguments(**kwargs)` works as expected.
  9. ```python
  10. def function_args_s1(p1, p2, /, pk1, pk2, *, k1, k2, **kwargs):
  11. pass
  12. function_args_s1(1, 2, 1, pk2=2, k1=1, k2=2, k3=3, k4=4)

but variable arguments(*args) meet some error.

  1. def function_args_s2(p1, p2, *args, /, pk1, pk2, *, k1, k2):
  2. pass
  3. SyntaxError: invalid syntax
  1. def function_args_s3(p1, p2, /, pk1, pk2, *args, k1, k2):
  2. pass
  3. pk1 and pk2 are no longer use keyword parameter because they before *args

答案1

得分: 1

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

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

然后

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

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

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

Then

  1. function_args_s2(1, 2, 3, 4, k1=5, k2=6)
  2. ()
  3. {}
  4. function_args_s2(1, 2, 3, 4, 5, 6, k1=7, k2=8, kw1=9, kw2=10)
  5. (5, 6)
  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:

确定