Python之可变长参数
可变长参数:
形参/实参: 实参和形参位置一一对应
def calc(x,y): x,y ->形参
res = x ** y
return res
result = calc(3,2) 3,2 ->实参
print(result)
结果:9
位置参数: 缺一不可,多一不行
def test(x,y,z): # x=1,y=2,z=3
print(x)
print(y)
print(z)
test(1,2,3) # 传入的参数位置与上面的x,y,z 一一对应
关键字参数:
test(y=1,x=3,z=2)
注意: 位置参数一定要在关键字参数的左边!!!
正确方式:
test(2,3,z=1)
默认参数:
def handle(x,type='mysql'): type - 即为传入的默认参数
print(x)
print(type)
handle('hello',type='oracle')
结果:
hello
oracle
handle('hi')
结果:
hi
mysql
参数组:** 和 *
*列表
def test(x,*args): #一次只传一个值 *args -> 留下可扩展性
print(x)
# print(args)
# print(args[1])
test(1,2,3,4,5)
test(1,*[2,3,4,5]) -> 以列表形式传值
结果:
1
(2,3,4,5)
3
**字典
def test(x,**kwargs):
print(x)
print(kwargs)
test(1,**{'a':2,'b':'3'}) -> 以字典形式传值
结果:
1
{'a':2,'b':'3'}
def test(x,*args,**kwargs):
print(x)
print(kwargs)
test(1,*['a',3,'c'],**{'a':2,'b':'3'}) -> 能够接收任意形式的传值
结果:
1
('a',3,'c')
{'a':2,'b':'3'}

浙公网安备 33010602011771号