在Python中,函数的参数主要可以分为以下三种类型:
1、可变参数
可变参数必须放在固定参数之后。
>>> def fun(a,b,*args):
print(a,b,args)
>>> fun(1,2,3,4,5)
1 2 (3, 4, 5)
2、关键字参数
必须成对传值:key = value
>>> d = dict(one=1,two=2,three=3,four=4)
>>> def fun(**kwargs):
print(kwargs)
>>> fun(**d)
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> fun(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
3、默认值参数
在定义函数时,给定其参数默认值,在调用时,若没有给该参数传值,则使用默认参数,若给定了,将忽略默认值。
>>> def fun(x,y=3):
print(x+y)
>>> fun(1)
4
>>> fun(1,2)
3
>>> fun(1,y=2)
3