gpt4 book ai didi

python - 为什么不能这样使用star运算符? def foo(* args,此=“default”,** kwargs)

转载 作者:行者123 更新时间:2023-12-03 08:22:12 25 4
gpt4 key购买 nike

这会很有趣:

def foo(*args, this="default", **kwargs):
pass



  File "foo.py", line 1
def foo(*args, this="default", **kwargs):
^
SyntaxError: invalid syntax

由于我有一组不可知的位置参数,一组不可知的关键字参数以及一个或两个已知的关键字参数,因此我的另一种选择是:

def foo(*args, **kwargs):
this = kwargs.pop("this", "default")
...

因此,由于似乎总是有一个很好的答案来说明为什么事情是这样,所以我想知道。为什么不允许这样做?

编辑:
谢谢@dano
Added in Python3

最佳答案

您想对this进行的操作是使其成为仅关键字的参数;没有办法提供位置参数。支持此功能是在Python 3.0中添加的。 Here是描述其添加以及其他相关增强的PEP。基本原理部分非常清楚地描述了该问题:

The current Python function-calling paradigm allows arguments to be specified either by position or by keyword. An argument can be filled in either explicitly by name, or implicitly by position.

There are often cases where it is desirable for a function to take a variable number of arguments. The Python language supports this using the 'varargs' syntax ('*name'), which specifies that any 'left over' arguments be passed into the varargs parameter as a tuple.

One limitation on this is that currently, all of the regular argument slots must be filled before the vararg slot can be.

This is not always desirable. One can easily envision a function which takes a variable number of arguments, but also takes one or more 'options' in the form of keyword arguments. Currently, the only way to do this is to define both a varargs argument, and a 'keywords' argument (**kwargs), and then manually extract the desired keywords from the dictionary.



基本上,这只是对varargs原始实现的限制,直到python 3才解决。

关于python - 为什么不能这样使用star运算符? def foo(* args,此=“default”,** kwargs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24966614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com