*args和**kwargs

2018-10-15  本文已影响0人  逍遥_yjz

1.*args

def testUseKwargs(f_arg, *args):
    print("first normal arg:", f_arg)
    print(type(args[0]))
    
    for arg in args[0]:
        print("another arg through *args:", arg)

if __name__ == '__main__':
    args = ("two", 3, 5)
    testUseKwargs('zero', args)

输出:

first normal arg: zero
<class 'tuple'>
another arg through *args: two
another arg through *args: 3
another arg through *args: 5

2.kwargs

2.1 合并1

def testUseKwargs2(f_arg, **kwargs):
    print(f_arg)
    for key, value in kwargs.items():
        print("{0} == {1}".format(key, value))
        if key == 'arg2':
            print(key, '===', value)
f_arg = '你好'
kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
testUseKwargs2(f_arg, **kwargs)

输出:

你好
arg3 == 3
arg2 == two
arg2 === two
arg1 == 5

2.2 合并2

谈一谈python中的魔法变量args和*kwargs

上一篇 下一篇

猜你喜欢

热点阅读