Python知识学习16——不定长参数

当我们不确定需要的参数个数时,可以使用不定长参数来作为形式参数。

不定长参数可以选择传递0~多个值,并将这些值保存为一个元组:

1
2
3
4
5
6
7
8
>>> def test(a, b, *args):
··· print("a = ", a)
··· print("b = ", b)
··· print("args = ", args)
>>> test(1, 2, 3, 4, 5)
a = 1
b = 2
args = (3, 4, 5)

当然不定长参数也可以接受0个参数:

1
2
3
4
5
6
7
>>> def test(a, b, *args):
··· print(a)
··· print(b)
··· print(args)
>>> test(1, 2)
1
2

不定长参数还有这样一种格式:结合字典的不定长参数:

1
2
3
4
5
6
7
8
9
10
>>> def test(a, b, *args, **kwargs):
··· print("a =", a)
··· print("b =", b)
··· print("args =", args)
··· print("kwargs =", kwargs)
>>> test(1, 2, 3, 4, 5)
a = 1
b = 2
args = (3, 4, 5)
kwargs = {}

若是这样给不定长参数传值,**kwargs并不会接收到值,因为我们需要以字典的方式传值

1
2
3
4
5
6
7
8
9
10
>>> def test(a, b, *args, **kwargs):
··· print("a =", a)
··· print("b =", b)
··· print("args =", args)
··· print("kwargs =", kwargs)
>>> test(1, 2, name = 3, age = 4, addr = 5)
a = 1
b = 2
args = ()
kwargs = {'name': 3, 'age': 4, 'addr': 5}

拆包:

如果需要直接给两种不定长参数分别传递元组和字典,应该怎么做呢?

1
2
3
4
5
6
7
8
9
10
11
12
>>> def test(a, b, *args, **kwargs):
··· print("a =", a)
··· print("b =", b)
··· print("args =", args)
··· print("kwargs =", kwargs)
>>> a = ("a", "b", "c")
>>> b = {"name":"Tom", "age":22}
>>> test(1, 2, a, b)
a = 1
b = 2
args = (('a', 'b', 'c'), {'name': 'Tom', 'age': 22})
kwargs = {}

可见,这并不是我们想要的结果,因为Python将我们传递的元组和字典都作为第一种不定长参数的元组的元素了。

但是如果我们这样传递实际参数,就可以分别为两种不定长形式参数赋值:

1
2
3
4
5
6
7
8
9
10
11
12
>>> def test(a, b, *args, **kwargs):
··· print("a =", a)
··· print("b =", b)
··· print("args =", args)
··· print("kwargs =", kwargs)
>>> a = ("a", "b", "c")
>>> b = {"name":"Tom", "age":22}
>>> test(1, 2, *a, **b)
a = 1
b = 2
args = ('a', 'b', 'c')
kwargs = {'name': 'Tom', 'age': 22}