python星号什么意思_星号*是什么意思在Python?

请参阅语言参考中的

Function Definitions。

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、付费专栏及课程。

余额充值