python 动态参数

zluxingzhe 2020-02-10

# 位置传递, 只有一个*时表示元组
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

相关推荐

wndong / 0评论 2020-07-09
chenshengzun / 0评论 2020-05-15
Wmeng0 / 0评论 2020-02-14