Python *args 和 **kwargs 的使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3394835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use of *args and **kwargs
提问by MacPython
So I have difficulty with the concept of *argsand **kwargs.
所以我对*argsand的概念有困难**kwargs。
So far I have learned that:
到目前为止,我已经了解到:
*args= list of arguments - as positional arguments**kwargs= dictionary - whose keys become separate keyword arguments and the values become values of these arguments.
*args= 参数列表 - 作为位置参数**kwargs= 字典 - 其键成为单独的关键字参数,而值成为这些参数的值。
I don't understand what programming task this would be helpful for.
我不明白这对什么编程任务会有帮助。
Maybe:
也许:
I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument?
我想输入列表和字典作为函数的参数,同时作为通配符,所以我可以传递任何参数?
Is there a simple example to explain how *argsand **kwargsare used?
有没有一个简单的例子来解释如何使用*args和**kwargs使用?
Also the tutorial I found used just the "*" and a variable name.
我发现的教程也只使用了“*”和一个变量名。
Are *argsand **kwargsjust placeholders or do you use exactly *argsand **kwargsin the code?
是*args和**kwargs刚才占位符或者你使用完全相同*args,并**kwargs在代码中?
采纳答案by Dave Webb
The syntax is the *and **. The names *argsand **kwargsare only by convention but there's no hard requirement to use them.
语法是*and**。名称*args和**kwargs只是按照惯例,但没有硬性要求使用它们。
You would use *argswhen you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:
*args当您不确定有多少参数可能会传递给您的函数时,您会使用它,即它允许您将任意数量的参数传递给您的函数。例如:
>>> def print_everything(*args):
for count, thing in enumerate(args):
... print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage
Similarly, **kwargsallows you to handle named arguments that you have not defined in advance:
同样,**kwargs允许您处理未事先定义的命名参数:
>>> def table_things(**kwargs):
... for name, value in kwargs.items():
... print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit
You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *argsand **kwargs. The named arguments come first in the list. For example:
您也可以将这些与命名参数一起使用。显式参数首先获取值,然后将其他所有内容传递给*argsand **kwargs。命名参数首先出现在列表中。例如:
def table_things(titlestring, **kwargs)
You can also use both in the same function definition but *argsmust occur before **kwargs.
您也可以在同一个函数定义中同时使用两者,但*args必须出现在**kwargs.
You can also use the *and **syntax when calling a function. For example:
您还可以在调用函数时使用*and**语法。例如:
>>> def print_three_things(a, b, c):
... print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat
As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a *both in the function definition and in the function call.
正如您在这种情况下所看到的,它获取项目的列表(或元组)并将其解包。通过这种方式,它将它们与函数中的参数相匹配。当然,您可以*在函数定义和函数调用中同时使用 a。
回答by John La Rooy
The names *argsand **kwargsor **kware purely by convention. It makes it easier for us to read each other's code
名称*args和**kwargs或**kw完全是约定俗成的。它使我们更容易阅读彼此的代码
One place it is handy is when using the struct module
一个方便的地方是使用 struct 模块时
struct.unpack()returns a tuple whereas struct.pack()uses a variable number of arguments. When manipulating data it is convenient to be able to pass a tuple to struck.pack()eg.
struct.unpack()返回一个元组,而struct.pack()使用可变数量的参数。在操作数据时,可以方便地将元组传递给struck.pack()例如。
tuple_of_data = struct.unpack(format_str, data)
... manipulate the data
new_data = struct.pack(format_str, *tuple_of_data)
without this ability you would be forced to write
没有这种能力,你将被迫写作
new_data = struct.pack(format_str, tuple_of_data[0], tuple_of_data[1], tuple_of_data[2],...)
which also means the if the format_str changes and the size of the tuple changes, I'll have to go back and edit that really long line
这也意味着如果 format_str 发生变化并且元组的大小发生变化,我将不得不返回并编辑那条非常长的行
回答by Mark van Lent
One place where the use of *argsand **kwargsis quite useful is for subclassing.
使用*args和**kwargs非常有用的一个地方是用于子类化。
class Foo(object):
def __init__(self, value1, value2):
# do something with the values
print value1, value2
class MyFoo(Foo):
def __init__(self, *args, **kwargs):
# do something else, don't care about the args
print 'myfoo'
super(MyFoo, self).__init__(*args, **kwargs)
This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class.
这样你就可以扩展 Foo 类的行为,而不必对 Foo 了解太多。如果您正在为可能会更改的 API 编程,这会非常方便。MyFoo 只是将所有参数传递给 Foo 类。
回答by Steven Mohr
*args and **kwargs are special-magic features of Python. Think of a function that could have an unknown number of arguments. For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). So you write this function:
*args 和 **kwargs 是 Python 的特殊魔法特性。考虑一个可能有未知数量参数的函数。例如,无论出于何种原因,您都希望拥有对未知数量的数字求和的函数(并且您不想使用内置 sum 函数)。所以你写了这个函数:
def sumFunction(*args):
result = 0
for x in args:
result += x
return result
and use it like: sumFunction(3,4,6,3,6,8,9).
并像这样使用它:sumFunction(3,4,6,3,6,8,9)。
**kwargs has a diffrent function. With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary.
**kwargs 有不同的功能。使用 **kwargs,您可以为函数提供任意关键字参数,并且可以将它们作为字典访问。
def someFunction(**kwargs):
if 'text' in kwargs:
print kwargs['text']
Calling someFunction(text="foo") will print foo.
调用 someFunction(text="foo") 将打印 foo。
回答by Felix Kling
Just imagine you have a function but you don't want to restrict the number of parameter it takes. Example:
想象一下你有一个函数,但你不想限制它需要的参数数量。例子:
>>> import operator
>>> def multiply(*args):
... return reduce(operator.mul, args)
Then you use this function like:
然后你使用这个函数,如:
>>> multiply(1,2,3)
6
or
>>> numbers = [1,2,3]
>>> multiply(*numbers)
6
回答by jchl
One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped:
*args 和 **kwargs 有用的一种情况是在编写需要能够接受任意参数以传递给被包装函数的包装函数(例如装饰器)时。例如,一个简单的装饰器,它打印被包装函数的参数和返回值:
def mydecorator( f ):
@functools.wraps( f )
def wrapper( *args, **kwargs ):
print "Calling f", args, kwargs
v = f( *args, **kwargs )
print "f returned", v
return v
return wrapper
回答by Yoni H
You can have a look at python docs (docs.python.org in the FAQ), but more specifically for a good explanation the mysterious miss args and mister kwargs (courtesy of archive.org)(the original, dead link is here).
您可以查看 python 文档(常见问题解答中的 docs.python.org),但更具体地说,为了更好地解释神秘的 args 小姐和 kwargs 先生(由 archive.org 提供)(原始的死链接在这里)。
In a nutshell, both are used when optional parameters to a function or method are used. As Dave says, *args is used when you don't know how many arguments may be passed, and **kwargs when you want to handle parameters specified by name and value as in:
简而言之,当使用函数或方法的可选参数时,两者都会使用。正如 Dave 所说,当您不知道可以传递多少个参数时使用 *args,当您想要处理由名称和值指定的参数时使用 **kwargs,如下所示:
myfunction(myarg=1)
回答by Rudi
These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function.
这些参数通常用于代理函数,因此代理可以将任何输入参数传递给目标函数。
def foo(bar=2, baz=5):
print bar, baz
def proxy(x, *args, **kwargs): # reqire parameter x and accept any number of additional arguments
print x
foo(*args, **kwargs) # applies the "non-x" parameter to foo
proxy(23, 5, baz='foo') # calls foo with bar=5 and baz=foo
proxy(6)# calls foo with its default arguments
proxy(7, bar='asdas') # calls foo with bar='asdas' and leave baz default argument
But since these parameters hide the actual parameter names, it is better to avoid them.
但是由于这些参数隐藏了实际的参数名称,因此最好避免使用它们。
回答by Kit
Here's an example that uses 3 different types of parameters.
这是一个使用 3 种不同类型参数的示例。
def func(required_arg, *args, **kwargs):
# required_arg is a positional-only parameter.
print required_arg
# args is a tuple of positional arguments,
# because the parameter name has * prepended.
if args: # If args is not empty.
print args
# kwargs is a dictionary of keyword arguments,
# because the parameter name has ** prepended.
if kwargs: # If kwargs is not empty.
print kwargs
>>> func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes at least 1 argument (0 given)
>>> func("required argument")
required argument
>>> func("required argument", 1, 2, '3')
required argument
(1, 2, '3')
>>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")
required argument
(1, 2, '3')
{'keyword2': 'foo', 'keyword1': 4}
回答by Wayne Werner
Here's one of my favorite places to use the **syntax as in Dave Webb's final example:
这是我最喜欢使用**Dave Webb 的最后一个示例中的语法的地方之一:
mynum = 1000
mystr = 'Hello World!'
print "{mystr} New-style formatting is {mynum}x more fun!".format(**locals())
I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!
与仅使用名称本身相比,我不确定它是否非常快,但键入起来要容易得多!

