星号*在Python中是什么意思?

马丁08:

*在Python中像在C中一样具有特殊含义吗?我在Python Cookbook中看到了这样的函数:

def get(self, *a, **kw)

您能向我解释一下还是指出我在哪里可以找到答案(Google将*解释为通配符,因此我找不到令人满意的答案)。

洛特

请参见《语言参考》中的“ 函数定义 ”。

如果存在表单*identifier,则将其初始化为接收任何多余位置参数的元组,默认为空元组。如果存在表单**identifier,则将其初始化为一个新字典,以接收任何多余的关键字参数,默认为一个新的空字典。

另请参见函数调用

假设知道位置和关键字参数是什么,下面是一些示例:

范例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")

如您在上面的示例中看到a, b, c的,foo函数签名中仅包含参数由于dk不存在,它们被放入args字典中。该程序的输出为:

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它们打包成一个元组,因此该程序的输出为:

a = testa
b = testb
c = testc
('excess', 'another_excess')

您还可以将字典或元组解压缩为函数的参数:

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',)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章