美文网首页python学习
2019-10-19 python 函数中*args 和 **k

2019-10-19 python 函数中*args 和 **k

作者: 可乐W | 来源:发表于2019-10-19 11:18 被阅读0次

*args 和 **kwargs的使用方法

1.函数中这种特殊的定义*arg和*kwargs,是用来给函数传递不定个数的参数。*arg(只有一个*)用来传递list数组,而**kwargs(两个*)用来传递dict字典

def test_var_args(farg, *args):

    print ("formal arg:", farg)

    for arg in args:

        print ("another arg:", arg)

test_var_args(1, "two", 3)

# Results:

formal arg: 1

another arg: two

another arg: 3

def test_var_kwargs(farg, **kwargs):

    print ("formal arg:", farg)

    for key in kwargs:

        print ("another keyword arg: %s: %s" % (key, kwargs[key]))

test_var_kwargs(farg=1, myarg2="two", myarg3=3)

# Results:

formal arg: 1

another keyword arg: myarg2: two

another keyword arg: myarg3: 3

2.调用函数时使用*arg和**kwargs

def test_var_args_call(arg1, arg2, arg3):

    print( "arg1:", arg1)

    print( "arg2:", arg2)

    print ("arg3:", arg3)

args = ("two", 3)

test_var_args_call(1, *args)

# Results:

arg1: 1

arg2: two

arg3: 3

def test_var_args_call(arg1, arg2, arg3):

    print ("arg1:", arg1)

    print ("arg2:", arg2)

    print ("arg3:", arg3)

kwargs = {"arg3": 3, "arg2": "two"}

test_var_args_call(1, **kwargs)

# Results:

arg1: 1

arg2: two

arg3: 3

相关文章

网友评论

    本文标题:2019-10-19 python 函数中*args 和 **k

    本文链接:https://www.haomeiwen.com/subject/ecbgmctx.html