函数分为位置参数和不定长参数。简单理解一下位置参数,可以接收单个实参;不定长参数可以接收多个实参,不定长参数又分为位置不定长参数(*args)和关键字不定长参数(**kwargs)。
调用函数时,位置参数是必传的,如果参数为空,代码会报语法错误;*args将接收的参数返回 元祖,如果参数为空,返回空的元祖;**kwargs将接收的参数返回字典,如果参数为空,返回空的字典。
我们在定义和调用函数时,要注意先后顺序,下面以定义函数为例,我演示正确的三种顺序。
第一种 同时定义位置参数,位置不定长参数,关键字不定长参数
从左到右: 位置参数a,位置不定长参数*args,关键字不定长参数**args。顺序不能颠倒。
def test(a,*args,**kwargs):
print(f'a的值:{a}') # 位置参数
print(f'args的值:{args}') # 位置不定长参数
print(f'kwargs的值:{kwargs}') # 关键字不定长参数,调用参数时格式 key=value
test(0,1,2,3,name='Cindy',age=27)
运行结果
第二种 同时定义位置参数和位置不定长参数
位置参数a写在位置不定长参数args前面。顺序不能颠倒。
def color(a,*args):
print(f'a的值:{a}') # 位置参数
print(f'args的值:{args}') # 位置不定长参数,调用参数时格式 key=value
color(10,20,30)
color(10) # 这里没有args参数,会返回空的元祖
运行结果
第三种 同时定义位置不定长参数和关键字不定长参数
位置不定长参数args写在位置不定长参数kwargs前面。顺序不能颠倒。
def flower(*args,**kwargs):
print(f'args的值:{args}') # 位置不定长参数
print(f'kwargs的值:{kwargs}') # 关键字不定长参数,调用参数时格式 key=value
flower(101,102,num=3,age=27)
flower(101,102) # 这里没有kwargs参数,会返回空字典
运行结果
最后演示错误的顺序,这样写会代码会报语法错误,请大家注意。