天天看点

Python中函数参数

Python中函数的参数是很灵活的,下面分四种情况进行说明。

(1) fun(arg1, arg2, ...)

这是最常见的方式,也是和其它语言类似的方式

下面是一个实例:

>>> def fun(x, y):
    return x - y

>>> fun(12, -2)
14      

(2) fun(arg1, arg2=value2, ...)

这种就是所谓的带默认参数的函数,调用的时候我们可以指定arg2的值,也可以省略。

下面是带默认参数的函数实例:

>>> def fun(x, y=0):
    return x - y

>>> fun(10)
10
>>> fun(10, -2)
12
>>> fun(10, y=2)
8
>>> fun(x=10, y=2)
8      

带默认参数的函数有如上四种调用方式,但是我们调用的时候参数的名称必须和函数定义的时候的参数一致,否则会报错:

>>> fun(a=10, b=2)

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    fun(a=10, b=2)
TypeError: fun() got an unexpected keyword argument 'a'      

(3) fun(*arg)

即不定长参数,不管实参有多少个,在函数内部都被存放在以形参名为标识符的tuple中

下面是一个实例

>>> def fun(*param):
    print(param)

>>> fun(12, 3, 4)
(12, 3, 4)      

(4) fun(**arg)

>>> def fun(**param):
    print(param)

>>> fun(sun=0, mon=1, tues=2)
{'sun': 0, 'mon': 1, 'tues': 2}