# 位置传递, 只有一个*时表示元组 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
# 装包,拆包 students = {"001": ("张三", 12), "002": ("李四", 13), "003": ("王五", 14)} # 定义时传两个*, 就是装包 def func_3(name, **kwargs): # **kwargs 装包 print("{}喜欢的角色:".format(name)) if isinstance(kwargs, dict): values = kwargs.values() print(values) for name, age in values: print("{}的年龄是:{}".format(name, age)) # 调用时传两个*,就是拆包 func_3("kobe", **students) # **students 将字典拆包 """ kobe喜欢的角色: dict_values([('张三', 12), ('李四', 13), ('王五', 14)]) 张三的年龄是:12 李四的年龄是:13 王五的年龄是:14 """