慕少森
看见函数定义在语言参考中。如果表格*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功能。自d和k不存在,它们被放入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',)