**(双星/星号)和*(星/星号)对参数有何作用?
这些函数定义中的 *args
和 **kwargs
意味着什么?
def foo(x, y, *args):
pass
def bar(x, y, **kwargs):
pass
请参阅**(双星/星号)和*(星号/星号)在函数调用中意味着什么?关于论证的补充问题。
What do *args
and **kwargs
mean in these function definitions?
def foo(x, y, *args):
pass
def bar(x, y, **kwargs):
pass
See What do ** (double star/asterisk) and * (star/asterisk) mean in a function call? for the complementary question about arguments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(28)
*args
和**kwargs
是常见的习惯用法,允许函数使用任意数量的参数,如 Python 教程中有关定义函数的更多信息。*args
将为您提供所有位置参数 作为元组:**kwargs
将为您提供所有关键字参数作为字典:
这两种习惯用法都可以与普通参数混合,以允许一组固定参数和一些可变参数:
也可以以相反的方式使用:
*l
的另一种用法习惯用法是在调用函数时解压参数列表。在 Python 3 中,可以在赋值的左侧使用
*l
(扩展可迭代解包),尽管它在此上下文中给出了一个列表而不是元组:Python 3 还添加了一个新的语义(请参阅 PEP 3102):
此类函数仅接受 3 个位置参数,以及
之后的所有内容*
只能作为关键字参数传递。注意:
Python
dict
在语义上用于关键字参数传递,是任意排序的。但是,在 Python 3.6+ 中,保证关键字参数记住插入顺序。“
**kwargs
中元素的顺序现在对应于关键字参数传递给函数的顺序。” - Python 3.6 中的新增功能。事实上,CPython 3.6 中的所有字典都会记住插入顺序作为实现细节,这成为 Python 3.7 中的标准。
The
*args
and**kwargs
are common idioms to allow an arbitrary number of arguments to functions, as described in the section more on defining functions in the Python tutorial.The
*args
will give you all positional arguments as a tuple:The
**kwargs
will give you allkeyword arguments as a dictionary:
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
It is also possible to use this the other way around:
Another usage of the
*l
idiom is to unpack argument lists when calling a function.In Python 3 it is possible to use
*l
on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:Also Python 3 adds a new semantic (refer PEP 3102):
Such function accepts only 3 positional arguments, and everything after
*
can only be passed as keyword arguments.Note:
A Python
dict
, semantically used for keyword argument passing, is arbitrarily ordered. However, in Python 3.6+, keyword arguments are guaranteed to remember insertion order."The order of elements in
**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6.In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, and this becomes standard in Python 3.7.
还值得注意的是,调用函数时也可以使用
*
和**
。这是一个快捷方式,允许您使用列表/元组或字典直接将多个参数传递给函数。例如,如果您有以下函数:您可以执行以下操作:
注意:
mydict
中的键的命名必须与函数foo
的参数完全相同。否则它会抛出一个TypeError
:It's also worth noting that you can use
*
and**
when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:You can do things like:
Note: The keys in
mydict
have to be named exactly like the parameters of functionfoo
. Otherwise it will throw aTypeError
:单个 * 意味着可以有任意数量的额外位置参数。
foo()
可以像foo(1,2,3,4,5)
一样调用。在 foo() 的主体中,param2 是一个包含 2-5 的序列。双 ** 意味着可以有任意数量的额外命名参数。
bar()
可以像bar(1, a=2, b=3)
一样调用。在 bar() 的主体中,param2 是一个包含 {'a':2, 'b':3 } 的字典,代码如下:
输出为
The single * means that there can be any number of extra positional arguments.
foo()
can be invoked likefoo(1,2,3,4,5)
. In the body of foo() param2 is a sequence containing 2-5.The double ** means there can be any number of extra named parameters.
bar()
can be invoked likebar(1, a=2, b=3)
. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }With the following code:
the output is
它们允许将函数定义为接受,并允许用户传递任意数量的参数、位置 (
*
) 和关键字 (**)。
定义函数
*args
允许任意数量的可选位置参数(参数),这些参数将被分配给名为args
的元组。**kwargs
允许任意数量的可选关键字参数(参数),这些参数将位于名为kwargs
的字典中。您可以(并且应该)选择任何适当的名称,但如果目的是使参数具有非特定语义,则 args 和 kwargs 是标准名称。
扩展,传递任意数量的参数
您还可以使用 *args 和 **kwargs 来传递来自列表(或任何可迭代)和字典(或任何映射)的参数,分别。
接收参数的函数不必知道它们正在被扩展。
例如,Python 2 的 xrange 没有明确期望
*args
,但由于它需要 3 个整数作为参数:再举一个例子,我们可以在
str.format
中使用 dict 扩展:Python 3 中的新增功能:仅使用关键字参数定义函数
您可以使用仅关键字参数 之后
*args
- 例如,这里,kwarg2
必须作为关键字参数给出 - 而不是位置:用法:
此外,
*
可以由本身指示后面仅包含关键字参数,而不允许无限的位置参数。在这里,
kwarg2
再次必须是显式命名的关键字参数:并且我们不能再接受无限的位置参数,因为我们没有
*args*
:同样,更简单,这里我们要求
kwarg
按名称给出,而不是按位置给出:在这个例子中,我们看到如果我们尝试按位置传递
kwarg
,我们会得到一个错误:我们必须显式地传递
kwarg
参数作为关键字参数。Python 2 兼容演示
*args
(通常表示“star-args”)和**kwargs
(星号可以通过说“kwargs”来暗示,但可以通过“double -star kwargs") 是 Python 中使用*
和**
表示法的常见习惯用法。这些特定的变量名称不是必需的(例如,您可以使用*foos
和**bars
),但背离惯例可能会激怒您的 Python 程序员同事。当我们不知道我们的函数将接收什么或我们可能传递多少参数时,我们通常会使用它们,有时甚至单独命名每个变量也会变得非常混乱和冗余(但在这种情况下,通常显式是比隐式的更好)。
示例 1
以下函数描述了如何使用它们并演示了行为。请注意,命名的
b
参数将被之前的第二个位置参数使用:我们可以使用
help(foo)
检查函数签名的在线帮助,它告诉我们让我们使用
foo(1, 2, 3, 4, e=5, f=6, g=7)
调用此函数,打印出:
示例 2
我们也可以调用它使用另一个函数,我们刚刚提供
a
:bar(100)
prints:示例 3:装饰器中的实际用法
好吧,也许我们还没有看到该实用程序。因此,想象一下您有几个函数,在区分代码之前和/或之后具有冗余代码。以下命名函数只是出于说明目的的伪代码。
我们也许能够以不同的方式处理这个问题,但我们当然可以使用装饰器提取冗余,因此我们下面的示例演示了
*args
和**kwargs
如何能够非常有效地处理这个问题。有用:现在每个包装函数都可以编写得更加简洁,因为我们已经分解了冗余:
并且通过分解我们的代码,其中
*args
和**kwargs
允许我们做,我们减少线路代码,提高可读性和可维护性,并为我们的程序中的逻辑提供唯一的规范位置。如果我们需要更改此结构的任何部分,我们都有一个地方可以进行每项更改。They allow for functions to be defined to accept and for users to pass any number of arguments, positional (
*
) and keyword (**
).Defining Functions
*args
allows for any number of optional positional arguments (parameters), which will be assigned to a tuple namedargs
.**kwargs
allows for any number of optional keyword arguments (parameters), which will be in a dict namedkwargs
.You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics,
args
andkwargs
are standard names.Expansion, Passing any number of arguments
You can also use
*args
and**kwargs
to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.The function recieving the parameters does not have to know that they are being expanded.
For example, Python 2's xrange does not explicitly expect
*args
, but since it takes 3 integers as arguments:As another example, we can use dict expansion in
str.format
:New in Python 3: Defining functions with keyword only arguments
You can have keyword only arguments after the
*args
- for example, here,kwarg2
must be given as a keyword argument - not positionally:Usage:
Also,
*
can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.Here,
kwarg2
again must be an explicitly named, keyword argument:And we can no longer accept unlimited positional arguments because we don't have
*args*
:Again, more simply, here we require
kwarg
to be given by name, not positionally:In this example, we see that if we try to pass
kwarg
positionally, we get an error:We must explicitly pass the
kwarg
parameter as a keyword argument.Python 2 compatible demos
*args
(typically said "star-args") and**kwargs
(stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the*
and**
notation. These specific variable names aren't required (e.g. you could use*foos
and**bars
), but a departure from convention is likely to enrage your fellow Python coders.We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).
Example 1
The following function describes how they can be used, and demonstrates behavior. Note the named
b
argument will be consumed by the second positional argument before :We can check the online help for the function's signature, with
help(foo)
, which tells usLet's call this function with
foo(1, 2, 3, 4, e=5, f=6, g=7)
which prints:
Example 2
We can also call it using another function, into which we just provide
a
:bar(100)
prints:Example 3: practical usage in decorators
OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.
We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how
*args
and**kwargs
can be very useful:And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:
And by factoring out our code, which
*args
and**kwargs
allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.让我们首先了解什么是位置参数和关键字参数。
下面是一个带有位置参数的函数定义示例。
这是一个带有位置参数的函数定义。
您也可以使用关键字/命名参数来调用它:
现在让我们研究一个使用关键字参数定义函数的示例:
您也可以使用位置参数来调用该函数:
所以我们现在知道函数定义为位置参数和关键字参数。
现在让我们研究“*”运算符和“**”运算符。
请注意,这些运算符可用于 2 个领域:
a) 函数调用
b) 函数定义
在 中使用“*”运算符和“**”运算符函数调用。
让我们直接看一个例子,然后讨论它。
因此请记住,
当在函数调用中使用“*”或“**”运算符时,
“*”运算符会将列表或元组等数据结构解包为函数定义所需的参数。
'**' 运算符将字典解包为函数定义所需的参数。
现在让我们研究一下函数定义中“*”运算符的使用。
示例:
在函数定义中,“*”运算符将接收到的参数打包到一个元组中。
现在让我们看一个在函数定义中使用“**”的示例:
在函数定义中,“**”运算符将接收到的参数打包到字典中。
因此请记住:
在函数调用中,“*”将元组或列表的数据结构解压为位置参数或关键字参数,以由函数定义接收。
在函数调用中,“**”将字典的数据结构解包为由函数定义接收的位置参数或关键字参数。
在函数定义中,“*”将位置参数打包到一个元组中。
在函数定义中,“**”将关键字参数打包到字典中。
Let us first understand what are positional arguments and keyword arguments.
Below is an example of function definition with Positional arguments.
So this is a function definition with positional arguments.
You can call it with keyword/named arguments as well:
Now let us study an example of function definition with keyword arguments:
You can call this function with positional arguments as well:
So we now know function definitions with positional as well as keyword arguments.
Now let us study the '*' operator and '**' operator.
Please note these operators can be used in 2 areas:
a) function call
b) function definition
The use of '*' operator and '**' operator in function call.
Let us get straight to an example and then discuss it.
So remember
when the '*' or '**' operator is used in a function call -
'*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.
'**' operator unpacks a dictionary into arguments needed by function definition.
Now let us study the '*' operator use in function definition.
Example:
In function definition the '*' operator packs the received arguments into a tuple.
Now let us see an example of '**' used in function definition:
In function definition The '**' operator packs the received arguments into a dictionary.
So remember:
In a function call the '*' unpacks data structure of tuple or list into positional or keyword arguments to be received by function definition.
In a function call the '**' unpacks data structure of dictionary into positional or keyword arguments to be received by function definition.
In a function definition the '*' packs positional arguments into a tuple.
In a function definition the '**' packs keyword arguments into a dictionary.
该表可以方便地在函数构造和函数调用中使用
*
和**
:这实际上只是为了总结 Lorin Hochstein 的答案,但我发现它很有帮助。
相关地:star/splat 运算符的使用已 在 Python 3 中扩展了
This table is handy for using
*
and**
in function construction and function call:This really just serves to summarize Lorin Hochstein's answer but I find it helpful.
Relatedly: uses for the star/splat operators have been expanded in Python 3
TL;DR
下面是 Python 编程中
*
和**
的 6 种不同用例:*args
:def foo(*args): pass
,这里foo
接受任意数量的位置参数,即以下调用有效foo(1)
,foo(1, 'bar')
**kwargs
接受任意数量的关键字参数:def foo(**kwargs ): pass
,这里 'foo' 接受任意数量的关键字参数,即以下调用有效foo(name='Tom')
,foo(name=' Tom',年龄=33)
*args, **kwargs
的位置和关键字参数数量:def foo(*args, **kwargs): pass
,此处为foo
接受任意数量的位置和关键字参数,即以下调用有效foo(1,name='Tom')
,foo(1, 'bar', name ='汤姆',年龄=33)
* 强制仅使用关键字参数:
def foo(pos1, pos2, *, kwarg1): pass
,此处* 意味着 foo 只接受 pos2 之后的关键字参数,因此
foo(1, 2, 3)
引发 TypeError 但foo(1, 2, kwarg1=3)
没问题。*_
表达对更多位置参数不再感兴趣(注意:这只是约定):def foo(bar, baz, *_): pass
表示(按照惯例)foo
在其工作中仅使用bar
和baz
参数,并会忽略其他参数。**_
表达对更多关键字参数不再感兴趣(注意:这只是约定):def foo(bar, baz, **_ ): pass
表示(按照惯例)foo
在其工作中仅使用bar
和baz
参数,并且将忽略其他参数。额外奖励:从 python 3.8 开始,可以在函数定义中使用
/
来强制仅使用位置参数。在以下示例中,参数 a 和 b 是仅位置,而 c 或 d 可以是位置或关键字,e 或 f 必须是关键字:BONUS 2 :这个答案对同一个问题也带来了一个新的视角,它分享了
*
的内容**
表示在函数调用
、函数签名
、for 循环
等中。TL;DR
Below are 6 different use cases for
*
and**
in python programming:*args
:def foo(*args): pass
, herefoo
accepts any number of positional arguments, i. e., the following calls are validfoo(1)
,foo(1, 'bar')
**kwargs
:def foo(**kwargs): pass
, here 'foo' accepts any number of keyword arguments, i. e., the following calls are validfoo(name='Tom')
,foo(name='Tom', age=33)
*args, **kwargs
:def foo(*args, **kwargs): pass
, herefoo
accepts any number of positional and keyword arguments, i. e., the following calls are validfoo(1,name='Tom')
,foo(1, 'bar', name='Tom', age=33)
*
:def foo(pos1, pos2, *, kwarg1): pass
, here*
means that foo only accept keyword arguments after pos2, hencefoo(1, 2, 3)
raises TypeError butfoo(1, 2, kwarg1=3)
is ok.*_
(Note: this is a convention only):def foo(bar, baz, *_): pass
means (by convention)foo
only usesbar
andbaz
arguments in its working and will ignore others.**_
(Note: this is a convention only):def foo(bar, baz, **_): pass
means (by convention)foo
only usesbar
andbaz
arguments in its working and will ignore others.BONUS: From python 3.8 onward, one can use
/
in function definition to enforce positional only parameters. In the following example, parameters a and b are positional-only, while c or d can be positional or keyword, and e or f are required to be keywords:BONUS 2: THIS ANSWER to the same question also brings a new perspective, where it shares what does
*
and**
means in afunction call
,functions signature
,for loops
, etc.*
和**
在函数参数列表中具有特殊用途。 <代码>*暗示参数是一个列表,而
**
暗示参数是一本字典。这允许函数采用任意数量的
论点
*
and**
have special usage in the function argument list.*
implies that the argument is a list and
**
implies that the argumentis a dictionary. This allows functions to take arbitrary number of
arguments
对于那些通过例子学习的人!
*
的目的是让您能够定义一个函数,该函数可以采用以列表形式提供的任意数量的参数(例如f(*myList)
)。**
的目的是让您能够通过提供字典来提供函数的参数(例如f(**{'x' : 1, 'y' : 2})
)。让我们通过定义一个函数来展示这一点,该函数接受两个普通变量
x
、y
,并且可以接受更多参数作为myArgs
,甚至可以接受更多参数为myKW
。稍后,我们将展示如何使用myArgDict
提供y
。注意事项
**
专门为字典保留。**
必须始终位于*
之后。For those of you who learn by examples!
*
is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g.f(*myList)
).**
is to give you the ability to feed a function's arguments by providing a dictionary (e.g.f(**{'x' : 1, 'y' : 2})
).Let us show this by defining a function that takes two normal variables
x
,y
, and can accept more arguments asmyArgs
, and can accept even more arguments asmyKW
. Later, we will show how to feedy
usingmyArgDict
.Caveats
**
is exclusively reserved for dictionaries.**
must come after*
, always.来自 Python 文档:
From the Python documentation:
*
表示接收变量参数作为元组**
表示接收变量参数作为字典使用如下:
1) single *
输出:
2) 现在
**
输出:
*
means receive variable arguments as tuple**
means receive variable arguments as dictionaryUsed like the following:
1) single *
Output:
2) Now
**
Output:
在 Python 3.5 中,您还可以在
list
、dict
、tuple
和set
显示中使用此语法(也可以有时称为文字)。请参阅PEP 488:其他解包概括。它还允许在单个函数调用中解压缩多个可迭代对象。
(感谢 mgilson 提供 PEP 链接。)
In Python 3.5, you can also use this syntax in
list
,dict
,tuple
, andset
displays (also sometimes called literals). See PEP 488: Additional Unpacking Generalizations.It also allows multiple iterables to be unpacked in a single function call.
(Thanks to mgilson for the PEP link.)
TL;DR
它将传递给函数的参数分别打包到函数体内的
list
和dict
中。当您像这样定义函数签名时:可以使用任意数量的参数和关键字参数来调用它。非关键字参数被打包到函数体内名为
args
的列表中,关键字参数被打包到函数体内名为kwds
的字典中。现在在函数体内,当调用函数时,有两个局部变量,
args
,它是一个具有值["this", "is a list of", "non- keywords", "arguments"]
和kwds
,它是一个dict
,其值为{"keyword" : "ligma", "options" : [1,2,3]}
这也可以反向工作,即从调用方一侧。例如,如果您有一个函数定义为:
您可以通过解包调用范围中的迭代或映射来调用它:
TL;DR
It packs arguments passed to the function into
list
anddict
respectively inside the function body. When you define a function signature like this:it can be called with any number of arguments and keyword arguments. The non-keyword arguments get packed into a list called
args
inside the function body and the keyword arguments get packed into a dict calledkwds
inside the function body.now inside the function body, when the function is called, there are two local variables,
args
which is a list having value["this", "is a list of", "non-keyword", "arguments"]
andkwds
which is adict
having value{"keyword" : "ligma", "options" : [1,2,3]}
This also works in reverse, i.e. from the caller side. for example if you have a function defined as:
you can call it with by unpacking iterables or mappings you have in the calling scope:
我想举一个其他人没有提到的例子
* 还可以解压一个生成器
来自Python3文档的例子
unzip_x will be (1, 2, 3), unzip_y will be (4, 5, 6 )
zip() 接收多个 iretable 参数,并返回一个生成器。
I want to give an example which others haven't mentioned
* can also unpack a generator
An example from Python3 Document
unzip_x will be (1, 2, 3), unzip_y will be (4, 5, 6)
The zip() receives multiple iretable args, and return a generator.
基于 nickd 的答案...
输出:
基本上,任意数量的位置参数都可以使用 * args 和任何命名参数(或 kwargs 又名关键字参数)都可以使用 **kwargs。
Building on nickd's answer...
Output:
Basically, any number of positional arguments can use *args and any named arguments (or kwargs aka keyword arguments) can use **kwargs.
除了函数调用之外,*args 和 **kwargs 在类层次结构中也很有用,并且还可以避免在 Python 中编写
__init__
方法。类似的用法可以在 Django 代码等框架中看到。例如,
子类可以被
实例化为
另外,具有仅对该子类实例有意义的新属性的子类可以调用基类
__init__
来卸载属性设置。这是通过 *args 和 **kwargs 完成的。 kwargs 主要用于使用命名参数来读取代码。例如,
可以将其实例化为
完整代码为 这里
In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write
__init__
method in Python. Similar usage can seen in frameworks like Django code.For example,
A subclass can then be
The subclass then be instantiated as
Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class
__init__
to offload the attributes setting.This is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,
which can be instatiated as
The complete code is here
给定一个有 3 个项目作为参数的函数,
想象这个玩具有一个三角形、一个圆形和一个矩形项目的袋子。那个包不能直接放。您需要打开袋子才能取出这 3 件物品,现在它们就装好了。 Python * 运算符执行此解包过程。
Given a function that has 3 items as argument
Imagine this toy with a bag of a triangle, a circle and a rectangle item. That bag does not directly fit. You need to unpack the bag to take those 3 items and now they fit. The Python * operator does this unpack process.
函数定义中的星号“*”将多个位置参数组合为一个元组参数。
函数调用中的星号“*”将序列分割为单独的位置参数。
函数定义中的双星号'**'将多个关键字参数组合为一个字典参数。
函数调用中的双星号“**”将字典类对象分割为单独的关键字参数。
The asterisk '*' in a function definition combines multiple positional arguments into a single tuple argument.
The asterisk '*' in a function call splits a sequence into individual positional arguments.
The double asterisk '**' in a function definition combines multiple keyword arguments into a single dictionary argument.
The double asterisk '**' in a function call splits a dictionary-like object into individual keyword arguments.
*args
和**kwargs
:允许您将可变数量的参数传递给函数。*args
:用于向函数发送非关键字可变长度参数列表:将生成:
**kwargs*
**kwargs
允许您将带关键字的可变长度参数传递给函数。如果你想处理函数中的命名参数,你应该使用 **kwargs。将产生:
*args
and**kwargs
: allow you to pass a variable number of arguments to a function.*args
: is used to send a non-keyworded variable length argument list to the function:Will produce:
**kwargs*
**kwargs
allows you to pass keyworded variable length of arguments to a function. You should use**kwargs
if you want to handle named arguments in a function.Will produce:
在函数中使用两者的一个很好的例子是:
A good example of using both in a function is:
这个示例将帮助您立即记住 Python 中的
*args
、**kwargs
甚至super
和继承。This example would help you remember
*args
,**kwargs
and evensuper
and inheritance in Python at once.*args(或 *any )表示每个参数
注意:您不能将参数传递给 *args
*args 是元组类型,
用于访问元素不要使用 *
**kwd
**kwd 或 **任何
这是一个字典类型
*args ( or *any ) means every parameters
NOTICE : you can don't pass parameters to *args
The *args is in type tuple
for access to elements don't use of *
The **kwd
**kwd or **any
This is a dict type
*args
是特殊参数,可以将 0 个或多个(位置)参数作为元组。**kwargs
是特殊参数,可以将 0 个或多个(关键字)参数作为字典。*在Python中,有2种参数位置参数和关键字参数:
*args
:例如,
*args
可以将0个或多个参数作为一个元组,如下所示:输出:
并且,在打印时
*args
,不带括号和逗号打印 4 个数字:输出:
And,
args
具有 tuple 类型:输出:
But,
* args
没有类型:输出(错误):
并且,普通参数可以放在
*args
之前,如下所示:输出:
但是,
**kwargs
不能放在 < code>*args 如下所示:输出(错误):
并且,普通参数不能放在
*args
之后,如下所示:输出(错误):
但是,如果普通参数有默认值,则可以将它们放在
*args
后面,如下所示:输出:
并且另外,
**kwargs
可以放在*args
之后,如下所示:输出:
**kwargs
:例如,
** kwargs
可以取 0 个或多个参数作为字典,如下所示:输出:
并且,在打印
*kwargs
时,打印 2 个键:输出:
并且,
kwargs
has dict类型:输出:
但是,
*kwargs
和**kwargs
没有类型:输出(错误):
并且,普通参数可以放在
**kwargs
之前,如下所示:输出:
而且,
*args
也可以放在之前**kwargs
如下所示:输出:
并且,普通参数和
*args
不能放在**kwargs
后面,如下所示:Output(错误):
对于
*args
和**kwargs
:实际上,您可以为
*args
和** 使用其他名称kwargs
如下所示。常规使用*args
和**kwargs
:输出:
*args
is the special parameter which can take 0 or more (positional) arguments as a tuple.**kwargs
is the special parameter which can take 0 or more (keyword) arguments as a dictionary.*In Python, there are 2 kinds of arguments positional argument and keyword argument:
*args
:For example,
*args
can take 0 or more arguments as a tuple as shown below:Output:
And, when printing
*args
, 4 numbers are printed without parentheses and commas:Output:
And,
args
has tuple type:Output:
But,
*args
has no type:Output(Error):
And, normal parameters can be put before
*args
as shown below:Output:
But,
**kwargs
cannot be put before*args
as shown below:Output(Error):
And, normal parameters cannot be put after
*args
as shown below:Output(Error):
But, if normal parameters have default values, they can be put after
*args
as shown below:Output:
And also,
**kwargs
can be put after*args
as shown below:Output:
**kwargs
:For example,
**kwargs
can take 0 or more arguments as a dictionary as shown below:Output:
And, when printing
*kwargs
, 2 keys are printed:Output:
And,
kwargs
has dict type:Output:
But,
*kwargs
and**kwargs
have no type:Output(Error):
And, normal parameters can be put before
**kwargs
as shown below:Output:
And also,
*args
can be put before**kwargs
as shown below:Output:
And, normal parameters and
*args
cannot be put after**kwargs
as shown below:Output(Error):
For both
*args
and**kwargs
:Actually, you can use other names for
*args
and**kwargs
as shown below.*args
and**kwargs
are used conventionally:Output:
上下文
**
解包使用字符串格式
除了本线程中的答案之外,这里还有其他地方未提及的另一个细节。这扩展了 Brad Solomon 的回答
使用
**
解包在使用 python 时也很有用 <代码>str.format。这有点类似于 python
f-strings
f-string但声明一个字典来保存变量会增加开销(f-string 不需要字典)。快速示例
Context
**
Use with string formatting
In addition to the answers in this thread, here is another detail that was not mentioned elsewhere. This expands on the answer by Brad Solomon
Unpacking with
**
is also useful when using pythonstr.format
.This is somewhat similar to what you can do with python
f-strings
f-string but with the added overhead of declaring a dict to hold the variables (f-string does not require a dict).Quick Example
最简单的解释就是*是*args,传递一个元组,**是**kwargs,传递一个字典。这些只是默认的通用名称。
The most simple explanation is just that * is *args, which passes a tuple, and ** is **kwargs, which passes a dictionary. Those are just general names that are default.
两者都是
*args
&**kwargs
允许我们将多个参数传递给 python 方法,但有一些差异如下所述:*args
用于按顺序传递 n 个参数就像数组一样,每个元素都会跟随并索引。
据我所知,
*args
是一个用逗号,
分隔的参数数组,所以如果你想在上面的foo
,它看起来像因此,如果您运行
它,它将按放置顺序打印参数:1,2,3...
**kwargs
在这里被称为关键字参数,您也可以传递可变数量的参数,但参数很像字典 k/v 对。
这些是
关键字
参数,它们是一组命名参数,这些参数作为键/值对
或字典
传递,由,
分隔> 如果有多个。因此,对于bar
您可以发送并可以在函数中单独读取它,如下所示
Both
*args
&**kwargs
allows us to pass multiple arguments/parameters to a python method but there are few differences explained below:*args
Is used to pass n-numbers of arguments in order much like a Array every element will follow and index.
As far as I know,
*args
is an array of arguments separated by comma,
so if you wanted to tofoo
above it will look likeso if you run
it will print arguments in order of placement as 1,2,3...
**kwargs
These are called keyword arguments here also you can pass variable numbers of arguments but the arguments are much like a dictionary k/v pair.
These are
keyword
arguments which are set of named arguments which are passed askey/value pair
ordictionary
separated by,
if multiple. So forbar
you can sendand can read it in the function individually as
def foo(param1, *param2):
是一个可以接受任意数量的*param2
值的方法,def bar(param1, **param2):< /code> 是一个可以接受任意数量的值的方法,其键为
*param2
param1
是一个简单参数。例如,Java中实现varargs的语法如下:
def foo(param1, *param2):
is a method can accept arbitrary number of values for*param2
,def bar(param1, **param2):
is a method can accept arbitrary number of values with keys for*param2
param1
is a simple parameter.For example, the syntax for implementing varargs in Java as follows:
带有 *args 和 **kwargs 的“无限”参数
*args
和**kwargs
只是向函数输入无限字符的一些方法,例如:"Infinite" Args with *args and **kwargs
*args
and**kwargs
are just some way to input unlimited characters to functions, like: