python-函数参数不固定

默认参数的应用场景:
1.默认安装
2.数据库连接,默认端口号
 
参数不固定的情况:
参数组:
args:将接收的位置参数转换成元组
def test(*args):
    print(args)
 
test(1,2,3,4)
test(*[1,2,3,4,5])
 
result:
(1, 2, 3, 4)
(1, 2, 3, 4, 5)
kwargs:把存入的N歌关键字参数转换成字典
 
def test2(**kwargs):
    print(kwargs)
 
test2(name='alex',age=8)
 
result:
{'name': 'alex', 'age': 8}
 
高阶函数:将函数作为参数
def add(x, y, f):
    return f(x) + f(y)
 
res = add(3, -6, abs)
print(res)
 
result:9
 
 

猜你喜欢

转载自www.cnblogs.com/feiyafei/p/9103564.html
今日推荐