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

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐