1.关键字参数和默认值
def say_hello(name,say) :
print("{},{}".format(name,say))
say_hello("say","hello") #say,hello
#可以看出参数是按照函数内的引用输出的,但参数的顺序有时难以记住
#关键字参数则可以帮助你
say_hello(name="say",say="hello")#say,hello
#避免有时会遇到参数过多搞混了的情况
say_hello("say",say="hello")##say,hello
#像这种混用的方式也是可以的,但不建议,除非参数很少
#定义函数时的参数和默认值也是可以设定的
def say_python(say="say",words="python") :
print("{},{}".format(say,words))
say_python(words="java") #say,java
#可以看出设置参数时的默认值,只在使用时参数为空才起作用
2.收集参数
#收集的方式有两种
*参数,将参数收集为元组
def fn_a(str,*num) :
print(str+":")
print(num)
fn_a("print",1,2,3,4,5)
# print:
# (1, 2, 3, 4, 5)
** 参数,收集关键字参数为字典
def fn_b(**params) :
print(params)
fn_b(name="lisa",age=17,sex="female")
#{'name': 'lisa', 'age': 17, 'sex': 'female'}
要注意的是,*参数,这种方法不会收集关键字参数
#收集的方法可以混用,举个例子
def fn_c(x,y,z=3,*others,**keypar) :
print(x,y,z)
print(others)
print(keypar)
fn_c(1,2,3,4,5,6,7,foo=11,bar=22)
# 1 2 3
# (4, 5, 6, 7)
# {'foo': 11, 'bar': 22}
3.分配参数
#与收集参数相反的操作,在使用函数时加或*
def fn_d(x,y) :
return x+y
d=[1,2]
print(fn_d(*d)) #3
def fn_e(x,y) :
print("{},{}".format(x,y))
e={"x":"say","y":"hello"}
fn_e(**e) #say,hello 这里注意一下键一定要和形参名称一致
#还有,如果定义和调用都使用*或**,将只传递元组和字典