织梦CMS - 轻松建站从此开始!

欧博ABG官网-欧博官方网址-会员登入

欧博官网What does asterisk * mean in Python?

时间:2026-01-21 06:54来源: 作者:admin 点击: 1 次
See in the Language Reference. If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulti

See in the Language Reference.

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.

Also, see .

Assuming that one knows what positional and keyword arguments are, here are some examples:

Example 1:

# Excess keyword argument (python 3) 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")

As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is:

a = testa b = testb c = testc {'k': 'another_excess', 'd': 'excess'}

Example 2:

# Excess positional argument (python 3) 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")

Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is:

a = testa b = testb c = testc ('excess', 'another_excess')

You can also unpack a dictionary or a tuple into arguments of a function:

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)

Prints:

a=testa b=testb c=testc args={'excessarg': 'string'}

And

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)

Prints:

a=testa b=testb c=testc args=('excess',)

(责任编辑:)
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:
发布者资料
查看详细资料 发送留言 加为好友 用户等级: 注册时间:2026-01-21 13:01 最后登录:2026-01-21 13:01
栏目列表
推荐内容