python 动态参数
# 位置传递, 只有一个*时表示元组 def func_1(*args): print(args) func_1(1) # (1,) func_1(1, 2) # (1, 2) func_1(1, 2, 3) # (1, 2, 3) list = [4, 5, 6] func_1(list) # ([4, 5, 6],)
# 关键字传递,2个**是表示字典 def func2(**kwargs): print(kwargs) func2(a=1) # {‘a‘: 1} func2(a=1, b=2) # {‘a‘: 1, ‘b‘: 2} func2(a=1, b=2, c=3) # {‘a‘: 1, ‘b‘: 2, ‘c‘:3}
# *args和**kwargs一起使用 def test_1(*args, **kwargs): print(args, type(args)) # (1, 2, 3) <class ‘tuple‘> print(*args) # 1 2 3 # 一个*时表示获取键值key print(*kwargs) # x y z test_2(**kwargs) # 22 33 44 def test_2(x, y, z): print(x) print(y) print(z) test_1(1, 2, 3, x=22, y=33, z=44)
# Demo def add(name, *args): sum = 0 if len(args) > 0: for i in args: sum = sum + i print(name + " 累加和是 sum:", sum) else: print("没有元素可以计算,sum:", sum) add("chenming", 1, 3, 5, 6) # chenming 累加和是 sum: 15
相关推荐
张荣珍 2020-11-12
goawalk 2020-10-29
ahailanjianj 2020-10-10
clong 2020-08-23
hell0kitty 2020-07-28
leodengzx 2020-07-04
JayFighting 2020-06-28
89510194 2020-06-27
小灯光环 2020-06-11
yunsaiqing 2020-06-06
弱思 2020-06-04
mysteryrat 2020-06-02
liqinglin0 2020-06-01
jvm 2020-05-30
curiousL 2020-05-27