**(双星/星号)和 *(星/星号)对参数有什么作用?
*Args
和 ** Kwargs
在这些功能定义中的意思是什么?
def foo(x, y, *args):
pass
def bar(x, y, **kwargs):
pass
参见在函数呼叫中是什么**(double star/asterisk)和 *(star/asterisk)的含义?关于参数的互补问题。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(28)
*
和**
在函数参数列表中具有特殊用法。*
暗示该参数是列表,
**
表示该参数是词典。这允许函数进行任意数量
争论
*
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
喂食。caveats
**
专门用于词典。**
必须始终以*
的形式出现。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)单*
output:
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> 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 IT
包装参数将函数传递到
list
和dict
内部内部的内部。当您定义这样的函数签名时:可以使用任何数量的参数和关键字参数调用。非关键字参数被包装到功能正文内的名为
args
的列表中,关键字参数被包装到函数主体内的dictkwds
中。现在在函数主体内,当调用函数时,有两个局部变量,
args
,它是具有值[“ this”,“”的列表,是“,”非 - 关键字“,”参数”]
和kwds
是dict
具有value{“ keyword”:“ ligma”,“ 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:
我想举一个尚未提及
*的示例 *也可以解开A Generator
python3文档unzip_x的示例
将为(1,2,3),unzip_y将为(4,5,6 )
zip()接收多个无与伦比的args,然后返回生成器。
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 aka关键字参数)都可以使用** 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中编写
__ INT __ INT __ INT __
方法。在Django代码等框架中可以看到类似的用法。例如,
一个子类可以作为
子类,然后像
一个新属性的子类实例化,该子类仅对该子类实例有意义,可以调用base类
__ INT __ INT __
以卸载属性设置。这是通过 *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.
函数定义 中的星号'*'将多个位置参数组合到单个 tuple 参数中。
函数中的星号'*'呼叫 splits a 序列 进入单个位置参数。
double atterisk'**'在函数定义 中,将多个关键字参数组合到单个 dictionary 参数中。
double atterisk'**'在函数 call splits a dictionary 类似的对象。
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:
此示例将帮助您记住
*Args
,** Kwargs
,甚至super
和sustaritance and python中的继承。This example would help you remember
*args
,**kwargs
and evensuper
and inheritance in Python at once.*args(或 *任何)表示每个参数
note :您不能将参数传递给 *arg arg
the *args在类型元组中
用于访问元素,而不使用 ***
kwd ** kwd
** KWD或**
这是一个dict类型
*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中,有两种参数 :
*args
:例如,
*args
可以服用0或更多参数为元组,如下所示:输出:
,当打印
*args
时,打印了4个数字,没有括号和逗号:输出:
和,
args
hap strong> tuple 类型:输出:
但是,
*args
没有类型:输出(错误):
,并且可以将普通参数放在
*args
之前,如下所示:输出:
但是,
** kwargs
不能在<之前放置代码>*args 如下所示:输出(错误):
和,在
*args
之后,不能放置普通参数,如下所示:输出(输出):
但是,如果正常参数具有默认值,则可以在
*args
之后放置它们,如下所示:输出:和输出:
和另外,
** kwargs
可以在*args
之后放置,如下所示:输出:
** kwargs
:例如,
** Kwargs
可以将0或更多参数作为词典,如下所示:输出:
和,当打印
*Kwargs
时,打印了2个密钥,打印了2个密钥:output:output:<
code:
Kwargs
具有 dict 类型:输出:
但是,
*Kwargs
和** kwargs
有无类型:输出(错误):
,可以将普通参数放在
** Kwargs
之前,如下所示:输出:
*Args
可以放在之前** kwargs
如下所示:输出:
和,正常参数和
*args
在** kwargs
后不能放置,如图所示。下图:输出(错误):
语法:
*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的答案上进行扩展
。代码> str.format 。
这与您可以使用Python
f-strings
f-string 有点相似。但是,随着宣布固定变量的额外开销(F串不需要命令)。快速示例
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
最简单的解释就是 *IS *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
&amp;** Kwargs
允许我们将多个参数/参数传递给Python方法,但是以下几乎没有差异:*ARGS
用于按顺序传递参数的n-numbers就像一个数组一样,每个元素都会遵循和索引。
据我所知,
*args
是一系列由comma ,隔开的参数,因此,如果您想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) 的键接受任意数量的值
*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:*args
和** kwargs
是常见的成语,可以允许任意数量的参数到函数,如有关定义的更多信息功能在Python教程中。*args
将为您提供所有位置参数作为元组:** Kwargs
将为您提供所有人关键字参数作为词典:
两个字典都可以与普通参数混合以允许一组固定和一些变量参数:
也可以以相反的方式使用它:
*l
的另一种用法习惯是打开参数列表调用函数时。在Python 3中,可以在分配的左侧使用
*L
(扩展的峰值解开包装),尽管它在这种情况下给出了一个列表,而不是元组:也添加了一个新的语义(请参阅 pep 3102 ):
这样的功能仅接受3个位置参数和3个位置参数和
*
之后的所有内容都只能以关键字参数传递。注意:
python
dict
是任意排序的,用于关键字参数传递的语义。但是,在Python 3.6+中,保证关键字参数记住插入顺序。“
** kwargs
中的元素顺序现在对应于将关键字参数传递给函数的顺序。” - python 3.6中的新事物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
从列表(或任何迭代)和dicts(或任何映射)中传递参数(或任何映射),分别。接收参数的功能不必知道它们正在扩展。
例如,Python 2的Xrange并未明确期望
*args
,但是由于它将3个整数作为参数:作为另一个例子,我们可以在
str.form.format
:python 3中的新事物:使用关键字定义函数,只有
您可以拥有 keyorth仅参数
args
- 例如,例如在这里,kwarg2
必须以关键字参数 - 不是位置:usage:
另外,
*
可以自己使用为了指出仅关键字的参数,而不允许无限的位置参数。在这里,
kwarg2
再次必须是一个明确命名的关键字参数:并且我们不能再接受无限的位置参数,因为我们没有
*args*
:同样,更简单,更简单地,在这里我们需要
kwarg
以名称给出,而不是定位:在此示例中,我们看到,如果我们尝试通过
kwarg
定位地传递kwarg
,我们会收到一个错误:我们必须明确将
kwarg
参数作为关键字参数传递。Python 2兼容演示
*args
(通常表示“ Star-Args”)和** Kwargs
(可以通过说“ Kwargs”来暗示星星,但请用“ Double” double Placklicit -Star Kwargs“)是Python的常见成语,用于使用*
和**
符号。这些特定的变量名称不需要(例如,您可以使用*foos
和** bars
),但是远离约定可能会激怒您的Python编码器。通常,当我们不知道我们的功能会收到什么或可能通过多少参数时,我们通常会使用这些,有时即使单独命名每个变量也会变得非常凌乱和多余(但这通常是显式的情况比隐式更好)。
示例1
以下功能描述了如何使用它们并演示行为。请注意,命名
b
参数将被第二个位置参数消费:我们可以使用
help(foo)
检查在线签名的在线帮助,这告诉我们让我们使用
foo(1,2,2,3,4,E = 5,f = 6,g = 7)
打印:
示例2
我们也可以称呼它使用另一个功能,我们只提供
a
:bar(100)
打印:示例3:装饰器中的实际用法
好,所以也许我们还没有看到该实用程序。因此,请想象您在差异化代码之前和/或之后具有多个具有冗余代码的功能。以下命名函数只是用于说明目的的伪代码。
我们可能能够以不同的方式处理此操作,但是我们当然可以用装饰器提取冗余,因此我们的下面示例演示了
*args
and 和** 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)功能定义
在函数调用。
让我们直接进入示例,然后进行讨论。
因此,请记住,
当在函数调用 -
'*'操作员将数据结构(例如列表或元组)解开为函数定义所需的参数中时,请记住'*'或'**'运算符时。
'**'运算符将字典解开为函数定义所需的参数。
现在,让我们研究功能定义中的“*”操作员使用。
示例:
在函数定义'*'操作员将接收到的参数包装成元组中。
现在,让我们查看函数定义中使用的“ **”的示例:
在函数定义'**'操作员将接收的参数包装到字典中。
因此,请记住:
在函数中调用'*'解开包装元组或列表的数据结构或通过功能定义接收到的位置或关键字参数。
在函数中调用'**' dunkaks 词典的数据结构是通过函数定义接收到的位置或关键字参数。
在函数中定义'*'包装位置参数成元组。
在函数中定义'**' packs 关键字参数中的字典。
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.
地使用
*
和**
在功能 construction 和function call :此表非常方便 总结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
:< /strong>def foo(** kwargs):通过
,在这里'foo'接受任何数量的关键字参数,即foo(name ='tom')
,foo(name ='tom',age = 33)
*args,** kwargs :
def foo(*args,** kwargs):Pass
,此处foo
接受任何数字位置和关键字参数,即,以下调用是有效的foo(1,name ='tom')
,foo(1,'bar',name ='tom',age = 33 )
*
来执行关键字:def foo(pos1,pos2, *,kwarg1):Pass
,此处*
表示FOO仅接受POS2之后的关键字参数,因此foo(1,2,3)
升高typeerror,但foo(1,2,kwarg1 = 3)
还可以。*_
(注意:仅是约定):def foo(bar,baz, *_):通过
(按照惯例)foo
仅使用bar
和baz
在其工作中参数,并且会忽略其他内容。** _
(注意:仅是约定),对更多关键字参数表示不进一步兴趣):def foo(bar,bar,baz,** _ ):通过
含义(按照惯例)foo
仅使用bar
和baz
在其工作中参数,并且会忽略其他。奖金:从Python 3.8开始,可以在功能定义中使用
/
来执行位置参数。在下面的示例中,参数a和b是仅位置 - ,而c或d可以是位置或关键字,而e或f必须为关键字:奖金2 :这个答案也带来了同样的问题透视图,它共享
*
和**
在函数呼叫
,function signature
,** 在哪里共享什么。 >用于循环,等等。
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.