使用 *args、**kwargs 和可选/默认参数调用 Python 函数 [英] Calling a Python function with *args,**kwargs and optional / default arguments
问题描述
在python中,我可以定义一个函数如下:
In python, I can define a function as follows:
def func(kw1=None,kw2=None,**kwargs):
...
在这种情况下,我可以调用 func 为:
In this case, i can call func as:
func(kw1=3,kw2=4,who_knows_if_this_will_be_used=7,more_kwargs=Ellipsis)
我还可以将函数定义为:
I can also define a function as:
def func(arg1,arg2,*args):
...
可以称为
func(3,4,additional,arguments,go,here,Ellipsis)
最后,我可以将两种形式结合起来
Finally, I can combine the two forms
def func(arg1,arg2,*args,**kwargs):
...
但是,调用是行不通的:
But, what does not work is calling:
func(arg1,arg2,*args,kw1=None,kw2=None,**kwargs): #SYNTAX ERROR (in python 2 only, apparently this works in python 3)
...
我最初的想法是这可能是因为一个函数
My original thought was that this was probably because a function
def func(arg1,arg2,*args,kw1=None):
...
可以称为
func(1,2,3) #kw1 will be assigned 3
所以这会给 3 应该被打包到 args 还是 kwargs 中引入一些歧义.但是,使用 python 3,可以指定仅关键字参数:
So this would introduce some ambiguity as to whether 3 should be packed into args or kwargs. However, with python 3, there is the ability to specify keyword only arguments:
def func(a,b,*,kw=None): #can be called as func(1,2), func(1,2,kw=3), but NOT func(1,2,3)
...
有了这个,似乎没有语法歧义:
With this, it seems that there is no syntactic ambiguity with:
def func(a,b,*args,*,kw1=None,**kwargs):
...
然而,这仍然会带来语法错误(使用 Python3.2 测试).我失踪有什么原因吗?并且,有没有办法获得我上面描述的行为(使用带有默认参数的 *args)——我知道我可以通过操作函数内部的 kwargs 字典来模拟这种行为.
However, this still brings up a syntax error (tested with Python3.2). Is there a reason for this that I am missing? And, is there a way to get the behavior I described above (Having *args with default arguments) -- I know I can simulate that behavior by manipulating the kwargs dictionary inside the function.
推荐答案
您可以在 Python 3 中做到这一点.
You can do that in Python 3.
def func(a,b,*args,kw1=None,**kwargs):
裸*
仅用于指定关键字参数而不接受带有*args
的可变数量的位置参数.您不使用两个 *
.
The bare *
is only used when you want to specify keyword only arguments without accepting a variable number of positional arguments with *args
. You don't use two *
s.
引用语法,在 Python 2 中,你有
To quote from the grammar, in Python 2, you have
parameter_list ::= (defparameter ",")*
( "*" identifier [, "**" identifier]
| "**" identifier
| defparameter [","] )
在 Python 3 中,您有
parameter_list ::= (defparameter ",")*
( "*" [parameter] ("," defparameter)*
[, "**" parameter]
| "**" parameter
| defparameter [","] )
包括在 *
参数之后提供附加参数的规定.
which includes a provision for additional parameters after the *
parameter.
更新:
最新的 Python 3 文档此处.
Latest Python 3 documentation here.
这篇关于使用 *args、**kwargs 和可选/默认参数调用 Python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!