位置参数
定义参数的顺序和调用参数传递值的顺序要一致
关键字参数
定义参数的时候设置一个默认值,当调用参数的时候不分配这个参数就会使用默认值
定义和调用的时候参数名要一致,顺序随便
def hello(greeting='hello',name='world'):
print('{} {}!'.format(greeting,name))
hello(name='YI',greeting='handson')
运行结果:
handson YI!
Process finished with exit code 0
关键字参数的优点:对于不变的参数值可以在设置的时候设置默认值
参数收集
收集参数:定义参数的时候使用星号,def 函数名(参数A,*参数B):
传参的时候如果超过2个,多余的都会保存在参数B中,元组形式,只有一个参数的话,参数B会是个空元组
带两个星号:可以收集关键字参数,返回的是字典形式
def num1(x,*y,z):
print(x,y,z)
def num2(x,**y):
print(x,y)
num1(1,2,3,4,5,z=6)
num2(1,a=2,b=3)
运行结果:
1 (2, 3, 4, 5) 6
1 {'a': 2, 'b': 3}
Process finished with exit code 0
关键字参数–字典
单个参数–元组(列表)
参数分配
在调用函数的时候使用*是解包,把变量a的字典内容解包成关键字参数赋值给函数
a={'y':1,'x':2}
def add(x,y):
return x+y
s=add(**a)
print(s)
3
Process finished with exit code 0
字典–关键字参数
元组(列表)–单个参数
在函数调用的时候也可使用*,一个代表传递元组,两个代表传递字典
调用和分配的时候都使用*,和都不用是一样的效果
参考链接:https://www.jianshu.com/p/0ed914608a2c
这里直接把y指向的元组赋值给了add
def add(*args):
x=0
for i in args:
x+=i
print(x)
y=(1,3)
add(*y)
应用
#关键字参数
#关键字参数
def story(**param):
print('{name} is {job}'.format_map(param))
story(name='yiyangqianxi',job='actor')
story(job='actor',name='yiyangqianxi')
data={'name':'yiyangqianxi','job':'actor'}
story(**data) #字典转为关键字参数,关键字再转为字典
del data['job']
story(job='singger',**data)
运行结果:
yiyangqianxi is actor
yiyangqianxi is actor
yiyangqianxi is actor
yiyangqianxi is singger
Process finished with exit code 0
#位置参数
def power(x,y,*other):
if other:
print('{}!'.format(other))
print(pow(x,y))
power(2,2,'yiyangqianxi')
a=(3,)*4
power(*a) #元组转为多个参数,多个参数转为元组,
运行结果:
('yiyangqianxi',)!
4
(3, 3)!
27
Process finished with exit code 0
调用参数的时候,直接调用元组列表或者字典,不适用*会报错(定义参数的时候是有*的话)
#混合使用
def num(start,stop=0,step=1):
if stop==0:
start,stop=stop,start #互换
result=[]
i=start
while i<stop:
result.append(i)
i+=step
print(result)
num(10)
运行结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Process finished with exit code 0