码迷,mamicode.com
首页 > 编程语言 > 详细

python函数不定长参数

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

标签:class   def   *args   不定长参数   war   hello   size   body   pytho   

 

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函数不定长参数

标签:class   def   *args   不定长参数   war   hello   size   body   pytho   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!