英文:
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)
{'kw1': 9, 'kw2': 10}
答案2
得分: -1
不要在相同的签名中同时使用 *args
和 /
。*args
允许多个参数,/
不允许。
英文:
Do not have *args
and /
in the same signature. *args
allows for multiple arguments, /
does not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论