Python 函数的可变参数

*args

接收任意多个位置参数

def test(*args):
    print(type(args), args)
    
test("a", ["b", "c"])

上面我们创建了一个简单地函数用来接收多个位置参数,执行后的结果为: <class 'tuple'> ('a', ['b', 'c'])
可以看出使用*args方式接收参数会将这些参数放到一个元祖中。此时我们会想到一个问题假如我们传递参数时并不想将整个列表作为参数,而是想将列表中的每一个元素分别作为参数传入应该怎么办呢?在解决这个问题前我们先看一段代码。

test_list = ["one", "two", "three"]

print(test_list)
print(*test_list)

执行后的结果为:

['one', 'two', 'three']
one two three

事情变得有趣了起来,我们发现 * 可以帮助我们对列表进行解包,因此我们可以利用这样的特性,将列表中的每一个元素分别作为参数传入函数。

def test(*args):
    print(type(args), args)
    
test_list = ["one", "two", "three"]
    
test("a", *test_list)

执行后的结果为: <class 'tuple'> ('a', 'one', 'two', 'three')

**kwargs

接收多个关键字参数

def test(**kwargs):
    print(type(kwargs), kwargs)
    
test(a="one", b="two", c="three")

上面我们创建了一个简单地函数用来接收多个关键字参数,执行后的结果为: <class 'dict'> {'a': 'one', 'b': 'two', 'c': 'three'}
可以看出使用*kwargs方式接收参数会将这些参数放到一个字典中。还是同样的问题,我们可不可以将一个字典中每一个键值对分别作为关键字参数传入呢?答案是可以的,与 * 的使用方法相同。

def test(**kwargs):
    print(type(kwargs), kwargs)
    
test_dict = {"a":"one", "b":"two", "c":"three"}
test(**test_dict, d="four")

执行后的结果为: <class 'dict'> {'a': 'one', 'b': 'two', 'c': 'three', 'd': 'four'}

需要注意,当我们想同时传入多个位置参数和关键字参数时,需要注意 *args 必须在 **kwargs 前面