Python 中的 *args and **kwargs(关键词:Python/)

版权声明:本文为博主原创文章,可以转载,但转载前请联系博主。 https://blog.csdn.net/qq_33528613/article/details/84243174

*** 让函数支持接收任意数目的参数,有函数定义和函数调用这 2 种情况。

在函数定义中,
(1)*args 收集任意多的 位置参数 到 1 个元组 args 中;
(2)**kwargs 收集任意多的 关键字参数 到 1 个字典 kwargs 中;
(3)还可以混合位置参数、*** 任意参数,实现灵活的调用。

在函数调用中,
(4)*args 可以 解包 元组、列表 args
(5)**kwargs 可以 解包 字典 kwargs

Python 3 中的 keyword-only 参数,
(6)在 Python 2 中会报错;
(7)出现在 *b 前面的参数可以按照位置或关键字来传递,b收集额外的位置参数到 1 个元组,*b后面的参数按照关键字来传递;
(8)在参数列表中使用 *,出现在 * 之前的参数按照位置或关键字来传递,* 之后的参数必须只按照关键字来传递。

# (1)
>>> def f1(*args):
	print args
>>> f()
()
>>> f1(1)
(1,)
>>> f1(1, 2)
(1, 2)
>>> f1(1, 2, 3)
(1, 2, 3)

# (2)
>>> def f2(**kwargs):
	print kwargs
>>> f()
{}
>>> f2(a=2)
{'a': 2}
>>> f2(a=2, b=4)
{'a': 2, 'b': 4}

# (3)
>>> def f3(a, *pargs, **kwargs):
	print a, pargs, kwargs	
>>> f3(1, 2, 3, b=4, c=5)
1 (2, 3) {'c': 5, 'b': 4}

# (4)
>>> def f4(a, b, c):
	print a, b, c
>>> args = (1, 2, 3)
>>> f4(*args)
1 2 3

>>> args = [1, 2, 3]
>>> f4(*args)
1 2 3

>>> kwargs = {'a':6, 'b':4, 'c':8}
>>> kwargs.keys()
['a', 'c', 'b']
>>> f4(*kwargs)
a c b

# (5)
>>> def f4(a, b, c):
	print a, b, c
>>> kwargs = {'a':6, 'b':4, 'c':8}
>>> f4(**kwargs)
6 4 8
# (6)Python 2 下会报错
>>> def f6(a, *b, c):
	print a, b, c
	
SyntaxError: invalid syntax
# (7)
>>> def f6(a, *b, c):
	print(a, b, c)

	
>>> f6(1, 2, c=3)
1 (2,) 3
>>> f6(a=1, c=3)
1 () 3
>>> f6(1, 2, 3)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    f6(1, 2, 3)
TypeError: f6() missing 1 required keyword-only argument: 'c'
# (8)
>>> def f8(a, *, b, c):
	print(a, b, c)

	
>>> f8(1, b=2, c=3)
1 2 3
>>> f8(a=1, b=2, c=3)
1 2 3
>>> f8(1, 2, 3)
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    f8(1, 2, 3)
TypeError: f8() takes 1 positional argument but 3 were given

参考文献:

  1. 《Python 学习手册(第 4 版)》 - 第 18 章 参数 - 特定的参数匹配模型 - P449——P471。

猜你喜欢

转载自blog.csdn.net/qq_33528613/article/details/84243174