多类型传值
- list类型给函数参数传值
- tuple类型给函数参数传值
- dictionary类型给函数参数传值
注意:list和tuple类型给函数参数传值的时候,元素的个数必须与函数参数的个数相等,且参数的顺序与list和tuple中的元素的顺序是完全一样的;dictionary类型给函数参数传值的时候,元素个数必须与函数的参数个数相等,且key的名字与函数中的参数的名字完全相同,字典中参数的顺序不作要求。
#/usr/bin/python
#coding:utf8
def fun(name, age) :
print "name is %s" %name
print "age is %d" %age
l = ['Gudio', 35]
fun(*l) #list给函数参数传值
print "-"*20
t = ('Bob',11)
fun(*t) #tuple给函数参数传值
print "-"*20
d = {"age":28, "name":"Brad"}
fun(**d) #dict给函数参数传值
print "-"*20
d1 = {"age1":28, "name1":"Brad"}
#fun(**d1) #这里是错误的,因为字典的key与函数行参的名字不能一一对应
print "-"*20
23行注释之前的输出结果如下:
name is Gudio
age is 35
--------------------
name is Bob
age is 11
--------------------
name is Brad
age is 28
--------------------
Traceback (most recent call last):
File "13.py", line 23, in <module>
fun(**d1) #这里是错误的,因为字典的key与函数行参的名字不能一一对应
TypeError: fun() got an unexpected keyword argument 'age1'
23行注释之后的输出结果如下:
name is Gudio
age is 35
--------------------
name is Bob
age is 11
--------------------
name is Brad
age is 28
--------------------
--------------------
传值冗余,参数个数任意
python的函数的参数个数可以固定,也可以参数个数是任意个数,如下所示:
#!/usr/bin/python
#coding:utf8
def fun(*args): # 参数个数任意
print args
t = (10, 21, 33)
fun(*t)
print '#'*20
fun() # 不传任意参数
print '#'*20
l = [1, 2, 3]
fun(*l)
print '#'*20
fun(100, 200, 300)
print '#'*20
def fun1(x , *args): #至少一个参数
print "x = ", x
print args
fun1(10, *t) # 10赋值给x 元组t赋值给args
print '#'*20
fun1(10, 11, 12, 13) #按照顺序,10赋值给x,11、12和13自动当作一个元组
print '#'*20
fun1(10) #按照顺序,10赋值给x,元组为空
print '#'*20
#以下是指定参数传值,有元组传值的时候,不可以指定传值,指定的话就需要字典来传值了
def fun2(**args): #参数个数为任意个数
print args
d = {'name':'Manni', 'age': 30}
fun2() #不传参数
print '#'*20
fun2(**d)
print '#'*20
fun2(x = 10, **d)
print '#'*20
def fun3(x, **args):
print "x = ", x
print "args = ", args
fun3(x = 10, y = 12)
print '#'*20
fun3(x = 10, **d)
print '#'*20