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.
假设知道位置参数和关键字参数是什么,下面是一些示例:
例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字典中。程序的输出是: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',)