python3-可变长度参数函数(*args 和 **kwargs)

时间:2021-08-25 21:25:36

简述:

  • *args:    可变长度元组参数
  • **kwargs: 可变长度字典参数


--------------------------------------------------------------------------------------------------

详解:

【*args】:可变长度元组参数

例1:

def hello_args(para1, *args):
    print("para1 :", para1)
    for arg in args:
        print("args:", arg)

    print("type(args):", type(args))

hello_args('hello', 'this', 'is', 'mc.meng')

输出:

para1 : hello
args: this
args: is
args: mc.meng
type(args): <class 'tuple'>

可以看到,函数hello_args把第一个参数传给了位置参数(positional arguments)para1,把剩下的参数作为一个元组传给了*args。

【**kwargs】:可变长度字典参数

例2:

def hello_kwargs(para1, **kwargs):
    print("para1 :", para1)
    for key, value in kwargs.items():
        print("{0} = {1}".format(key, value))
    print("type(kwargs):", type(kwargs))


hello_kwargs("hello", key1=1, key2=2, key3=3)

输出:

para1 : hello
key1 = 1
key2 = 2
key3 = 3
type(kwargs): <class 'dict'>

或者还你可以把直接传入一个字典:

例3:

def hello_kwargs(para1, **kwargs):
    print("para1 :", para1)
    for key, value in kwargs.items():
        print("{0} = {1}".format(key, value))
    print("type(kwargs):", type(kwargs))


thiskw = {"key1": 1, "key2": "two", "key3": 3}
hello_kwargs("hello", **thiskw)

输出:

para1 : hello
key1 = 1
key2 = two
key3 = 3
type(kwargs): <class 'dict'>

但请注意:实参thiskw前面的**