1、*在函数调用中的作用
首先定义一个函数,并调用
def fun(a, b, c): print a, b, c fun(1,2,3)
则该函数的输出为
1 2 3
传递3个参数调用该函数,则该函数会打印出这三个参数
接下来,创建一个3个元素的列表,并使用*进行调用
l = [1,2,3]
fun(*l)
则输出同样为
1 2 3
在这里*号的作用是,将l中的的值进行了unpack,并作为相应位置的参数传递进fun函数中。
如果使用如下代码:
l=[3,5,6,9]
fun(*l)
则会因为函数数量问题产生错误:
TypeError Traceback (most recent call last) xxxx in <module>() TypeError: fun() takes exactly 3 arguments (4 given)
2、*args在函数调用中的作用
现在改变函数的定义,并进行调用
def fun(*args): print args fun(1)
则输出为
(1,)
或者使用任意多个参数进行调用,例如
fun(1,2,3)
这样的话,输出就是(1, 2, 3)
*args在函数定义中的作用是
接收所有形参后面的定位参数(positional arguments),并存储至一个元组中。所以args将会是一个元组。
如果将*args与形参进行混合,例如
def fun(a, *args): print "a is ", a print "args is ", args fun(1, 2, 3, 4)
则调用后的输出为
a is 1
args is (2, 3, 4)
我们可以看到,a被第一个位置的参数赋值为1,args接收了包含所有其他参数的tuple。