- 不定参数
即传入的参数个数不确定,任意几个都可以
在args前添加*
Example 01
def mysum(*args):
return args
res=mysum(20,30,40)
print(res)
结果
(20, 30, 40)
- 当含有形参时,将形参之外的实参以元组的形式传入
Example 02
def mysum(param1,param2,*args):
print(args)
return sum(args)
res=mysum(20,30,40,50,100)
print(res
结果
(40, 50, 100)
190
- 在形参参数名前添加**,将关键字传入的部分,作为字典传入
Example 03
def showUser(**kwargs):
print(kwargs)
showUser(name="liar",sex="woman",age=18,height=165,weight=50)
结果
{'name': 'liar', 'sex': 'woman', 'age': 18, 'height': 165, 'weight': 50}
- 同时含有形参与不定参
- 参数顺序
无默认值形式参数
有默认值形式参数
元组形式不定参数
关键字形式不定参数
Example 04
def test(a,b,c=10,*args,**kwargs):
print(a,b,c,args,kwargs)
test(1,2,3,4,5,d=11,f=13,g=19)
结果
1 2 3 (4, 5) {'d': 11, 'f': 13, 'g': 19}
- 传入实参时,当在实参前使用 * 的时候,会将元组解包成对应的实参
Example 05
def test(a,b,c,d):
print(a,b,c,d)
test(*(10,20,30,40))
结果
10 20 30 40
- 传入实参时,当在实参前使用两个 ** 的时候,会将字典解包成对应的关键字参数
Example 06
def test(a,b,c,d):
print(a,b,c,d)
data={"a":10,"b":20,"d":30,"c":40}
test(**data)
结果
10 20 40 30