首页 > 编程语言 > 详细

python函数不定长参数

时间:2017-12-31 23:21:26      阅读:277      评论:0      收藏:0      [点我收藏+]

 

def fun(a, b, *args):
    print(a)
    print(b)
    print(args)
    print("="*30)
    ret = a + b
    for i in args:
        ret += i
    return ret

print(fun(1,2,3,4))

结果:
1
2
(3, 4)
==============================
10

1,2分别赋值给a,b,剩下的参数以元组的形式赋值给args

 

字典形式参数:

def fun(a, b, *args, **kwargs):
    print(a)
    print(b)
    print(args)
    print(kwargs)

fun(1, 2, 3, 4, name = "hello", age = 20)

结果:
1
2
(3, 4)
{name: hello, age: 20}

 

传入元组和字典:

def fun(a, b, *args, **kwargs):
    print(a)
    print(b)
    print(args)
    print(kwargs)

tup = (11,22,33)
dic = {"name":"hello", "age":20}
fun(1, 2, *tup, **dic)

结果:
1
2
(11, 22, 33)
{name: hello, age: 20}

 

python函数不定长参数

原文:https://www.cnblogs.com/xhcdream/p/8159231.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!