python中星号代表什么意思,星号*在Python中是什么意思?

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值