这两种用法其实都是用来将任意个数的参数导入到 Python 函数中。这两个用法可以同时出现在一个函数中。
单星号(*):*agrs。将所有参数以元组(tuple)的形式导入
双星号(**):**kwargs。将参数以字典的形式导入
例:
def foo(a, b=10, *args, **kwargs):
print (a)
print (b)
print (args)
print (kwargs)
foo(1, 2, 3, 4, e=5, f=6, g=7)
输出结果为:
1
2
(3, 4)
{'e': 5, 'f': 6, 'g': 7}
此外,这两个符号也与位置参数(Positional arguments)和关键字参数(keyword arguments)有关,详情可参阅:
python函数的位置参数(Positional)和关键字参数(keyword) - 知乎
——————————————
另注星号*的另一种用法:
Unpacking Argument Lists
call with the
*
-operator to unpack the arguments out of a
list or
tuple:
>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]