例1:
#定义一个含有不定长参数的函数,本例第三个参数*args
def sum_nums(a,b,*args):
print('_'*30)
print(a)
print(b)
print(args)
#调用函数:
sum_nums(11,22,33,44,55,66,77)
sum_nums(11,22,33)
sum_nums(11,22)
sum_nums(11)#错误调用,传递的参数不够
#输出结果:
______________________________
11
22
(33, 44, 55, 66, 77)
______________________________
11
22
(33,)
______________________________
11
22
()
Traceback (most recent call last):
File "6.py", line 10, in <module>
sum_nums(11)#错误调用
TypeError: sum_nums() missing 1 required positional argument: 'b'
例2:
#定义一个含有复杂参数类型的函数,**kwargs为关键字参数
def test(a,b,c=33,*args,**kwargs):
print(a)
print(b)
print(c)
print(args)
print(kwargs)
#函数调用
test(11,22,33,44,55,task=99,done=89)
#输出结果:
11
22
33
(44, 55)
{'task': 99, 'done': 89}
例3:拆包
#定义函数
def test(a,b,c=33,*args,**kwargs):
print(a)
print(b)
print(c)
print(args)
print(kwargs)
A=(11,22,33)
B={
'task':99,'done':89
}
#函数调用,将A拆开后传给args,将B拆开后传给kwargs
test(11,22,33,*A,**B)
#输出结果
11
22
33
(11, 22, 33)
{'task': 99, 'done': 89}