Python *args **kwargs 函数传参

我们写程序时,不确定要往函数中传入多少个参数,即可使用可变参数(不定长参数),用 *args**kwargs 表示。

*args 被称为 Non-keyword Variable Arguments,无关键字参数。

**kwargs 被称为 Keyword Variable Arguments,有关键字参数。

*args 以列表或者元组形式传参,**kwargs 以字典形式传参。

*args 实例:

当位置参数和不定长参数一起使用时,先把参数分配给位置参数,再将多余的参数以元组形式分配给 args

1
2
3
4
5
6
7
8
9
10
11
12
def test(a, b, *args):
c = args
print(a, b, c)

# 给的参数多于位置参数时的输出结果:
test("this is", "a", "test", "for", "args")
this is a ('test', 'for', 'args')

# 给的参数等于位置参数时的输出结果:
test("this is a", "test")
this is a test ()
# args 为空列表

**kwargs 实例:

当传入参数为字典时,使用 **kwargs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def test_kwargs(a, *args, **kwargs):
print(a)
print(args)
print(kwargs)

# 传入 key 和 value
# input
test_kwargs(1, f=1, s=2)

# output
1
()
{'f': 1, 's': 2}

# 传入整个字典
# input
a, b, c = 1, ['1', '2', '3'], {'f':1, 's':2, 't':3}
test_kwargs(a, b, **c) # 注意字典参数前要加 `**`

# output
1
(['1', '2', '3'],)
{'f': 1, 's': 2, 't': 3}

Python *args **kwargs 函数传参
https://pandintelli.github.io/2022/01/17/Python-Variable-Length-Parameters/
作者
Pand
发布于
2022年1月17日
许可协议