函数的参数除了上篇文章的一种方式以外,还可以有多种形式。例如在调用某些函数时,可以选择是否向其传递参数,而函数都可以正确调用;还有一些情况,比如函数中的参数数量不确定。这些情况应该怎么确定参数呢?
默认值参数
声明参数的时候,可以预先为参数设置一个默认值,当调用函数,如果某个参数有默认值,就可以不向函数传递该参数,如下:
def <函数名> (参数=默认值):
<函数体>
⚠️:如果在声明某一参数时,其参数列表中既包含无默认值参数,又包含默认值参数,那么声明函数的参数时,必须先声明无默认值的参数,后声明有默认值的参数(与C++的参数缺省相同)
参数传递
我们之前见到的传递方式是按照声明时的参数位置顺序来进行传递的,即位置参数。而实际上 python 还提供了另外一种传递参数的方法——按照参数名传递值的方法,即提供关键字参数,提供关键字参数的函数调用类似于定义函数时设置参数的默认值。
具体方法是:在调用函数时,在调用函数名后的圆括号里面写出关键字=参数值
的形式
>>> def func1 (add, T = [1,2]):
... result = 0
... for i in T:
... result += i
... result += add
... return result
...
>>> func1(1,[1,2,3])
7
>>> func1(1,[1,2])
4
>>> func1(1)
4
>>> func1(T = [4,5,7], add = 8)
24
🌙 当带有多个缺省参数的函数被调用时,可单独指定某个缺省参数的值。如:
def print_info(name, age = 18,gender = True )
print_info("zhan", gender = False )
可变数量参数传递
在自定义函数时,如果在参数名前加一个星号 “*”,则表示该参数是一个可变长参数。在调用该函数时,如果依次将其他变量都赋予值之后,剩下的参数就收集在一个元组中,元组的名字就是前面带✳️的参数名。
例如:
>>> def change_para_num(*tpl):
... print(type(tpl))
... print(tpl)
...
>>> change_para_num(1)
<class 'tuple'>
(1,)
>>> change_para_num(1,2,3)
<class 'tuple'>
(1, 2, 3)
说明:定义了一个函数
change_para_sum(*tpl)
,只有一个带星号的参数
当自定义函数时,参数中含有前面所介绍的三种类型的参数,则一般来说带星号的参数应该放在最后。
带星号的参数放在最前面时,仍然可以正常工作,但调用时后面 的参数必须以关键字参数方式提供,否则会因其后位置参数无法获取值而引发错误。例如:
>>> def change_para_num(*tpl, a, b = 0):
... print('tpl:',tpl)
... print('a:',a)
... print('b:',b)
...
>>> change_para_num(1,2,3,a=5)
tpl: (1, 2, 3)
a: 5
b: 0
>>> change_para_num(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: change_para_num() missing 1 required keyword-only argument: 'a'
出现的问题是:a 变量没有默认值,也不能获取值(进元组里面了)
调整
使用元组来收集参数时,调用时提供的参数不能为关键字参数,如果要收集不定数量的关键字参数,可以在自定义函数时的参数前加两颗星,即**valuename
,这样一来,多余的关键字参数就可以以字典的形式被收集到valuename
中,⚠️收集关键字参数时要放到函数声明的参数列表中所有参数之后例如:
>>> def cube (name, *trace, **parameters):
... nature_parameters = {'x':1,
... 'y':1,
... 'z':1,
... 'colour':'white',
... 'weight':1}
... nature_parameters.update(parameters)
... print('the nature of the',name,'cube') ... print('the volumn of the cube is:',nature_parameters['x']*nature_parameters['y']*nature_parameters['z'])
... print('the colour of the cube is:',nature_parameters['colour']) ... print('the weight of the cube is:',nature_parameters['weight'])
... print('the former keepers are:',trace)
...
>>> cube ('first')
the nature of the first cube
the volumn of the cube is: 1
the colour of the cube is: white
the weight of the cube is: 1
the former keepers are: ()
>>> cube ('second',1)
the nature of the second cube
the volumn of the cube is: 1
the colour of the cube is: white
the weight of the cube is: 1
the former keepers are: (1,)
>>> cube ('third',1,2,x=4,colour='violet')
the nature of the third cube
the volumn of the cube is: 4
the colour of the cube is: violet
the weight of the cube is: 1
the former keepers are: (1, 2)