星号 * 在 Python 中是什么意思? [英] What does asterisk * mean in Python?
问题描述
* 在 Python 中是否与在 C 中一样具有特殊含义?我在 Python Cookbook 中看到了这样一个函数:
Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook:
def get(self, *a, **kw)
能否请您向我解释一下或指出我在哪里可以找到答案(Google 将 * 解释为通配符,因此我找不到满意的答案).
Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find a satisfactory answer).
推荐答案
参见 语言参考中的功能定义.
如果表单 *identifier
是目前,它被初始化为一个元组接收任何多余的位置参数,默认为空元组.如果表单 **identifier
是目前,它被初始化为一个新的字典收到任何多余的关键字参数,默认为新的空字典.
If the form
*identifier
is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form**identifier
is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.
另请参阅函数调用.
假设你知道什么是位置参数和关键字参数,这里有一些例子:
Assuming that one knows what positional and keyword arguments are, here are some examples:
示例 1:
# Excess keyword argument (python 2) example:
def foo(a, b, c, **args):
print "a = %s" % (a,)
print "b = %s" % (b,)
print "c = %s" % (c,)
print args
foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")
正如你在上面的例子中看到的,我们在foo
函数的签名中只有参数a, b, c
.由于 d
和 k
不存在,它们被放入 args 字典中.程序的输出为:
As you can see in the above example, we only have parameters a, b, c
in the signature of the foo
function. Since d
and k
are not present, they are put into the args dictionary. The output of the program is:
a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}
示例 2:
# Excess positional argument (python 2) example:
def foo(a, b, c, *args):
print "a = %s" % (a,)
print "b = %s" % (b,)
print "c = %s" % (c,)
print args
foo("testa", "testb", "testc", "excess", "another_excess")
这里,由于我们正在测试位置参数,多余的必须放在最后,并且 *args
将它们打包成一个元组,所以这个程序的输出是:
Here, since we're testing positional arguments, the excess ones have to be on the end, and *args
packs them into a tuple, so the output of this program is:
a = testa
b = testb
c = testc
('excess', 'another_excess')
您还可以将字典或元组解包为函数的参数:
You can also unpack a dictionary or a tuple into arguments of a function:
def foo(a,b,c,**args):
print "a=%s" % (a,)
print "b=%s" % (b,)
print "c=%s" % (c,)
print "args=%s" % (args,)
argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
foo(**argdict)
打印:
a=testa
b=testb
c=testc
args={'excessarg': 'string'}
和
def foo(a,b,c,*args):
print "a=%s" % (a,)
print "b=%s" % (b,)
print "c=%s" % (c,)
print "args=%s" % (args,)
argtuple = ("testa","testb","testc","excess")
foo(*argtuple)
打印:
a=testa
b=testb
c=testc
args=('excess',)
这篇关于星号 * 在 Python 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!