python参数中*号的用法实例

关于python函数参数中 * 的用法实例:

"""
一个位置参数,一个关键字参数
"""
def test1(arg1, *, arg2):
    print(arg1, arg2)

test1(1, arg2=2)
# 1 2

"""
一个位置参数,一个位置参数的元组
"""
def test2(arg1, *arg2):
    print(arg1, arg2)

test2(1, 2, 3)
# 1 (2, 3)
test2(1, (2, 3))
# 1 ((2, 3),)
test2(1, *(2, 3))
# 1 (2, 3)
test2(1, *[2, 3])
# 1 (2, 3)

"""
一个位置参数,一个关键字参数的字典
"""
def test3(arg1, **kwargs):
    print(arg1, kwargs)

test3(1, arg2=2, arg3=3)
# 1 {'arg2': 2, 'arg3': 3}
test3(1, **{'arg2': 2, 'arg3': 3})
# 1 {'arg2': 2, 'arg3': 3}

"""
一个位置参数元组,一个关键字参数的字典
"""
def test4(*args, **kwargs):
    print(args, kwargs)

test4(1, 2, 3, arg2=2, arg3=3)
# (1, 2, 3) {'arg2': 2, 'arg3': 3}
test4(1, 2, 3, **{'arg2': 2, 'arg3': 3})
# (1, 2, 3) {'arg2': 2, 'arg3': 3}
test4(*(1, 2, 3), **{'arg2': 2, 'arg3': 3})
# (1, 2, 3) {'arg2': 2, 'arg3': 3}
test4(arg2=2, arg3=3, *(1, 2, 3))
# (1, 2, 3) {'arg2': 2, 'arg3': 3}
python参数中*号的用法实例

原文链接:https://beltxman.com/4220.html,若无特殊说明本站内容为 行星带 原创,未经同意禁止转载。

发表评论

您的电子邮箱地址不会被公开。

Scroll to top