可变参数*args和可变参数**kwargs
(1)二者共同点:这两个参数都是表示给函数传不定数量的参数,即:我们不确定最后调用这个函数的时候会传递多少参数,也叫可变参数
(2)二者区别:
1)*args接收不定量的非关键字参数,返回一个元组。代码如下:
def testFun(*args):
print(type(args))
print(args)
for i in args:
print(i)
testFun(1, 2, 'hello')
print('-----------')
testFun((1, 2, 'hello'))
# 输出:
<class 'tuple'>
(1, 2, 'hello')
1
2
hello
-----------
<class 'tuple'>
((1, 2, 'hello'),)
(1, 2, 'hello')
def testFun(a, b, *args): # 注意:*args必须放在最后,否则会报错
print(args)
for i in args:
print(i)
print(a)
print(b)
testFun(1, 2, 'hello', ['a', 'b', 'c'])
# 输出
('hello', ['a', 'b', 'c'])
hello
['a', 'b', 'c']
1
2
2)**kwargs接收不定量的关键字参数,返回一个字典,代码如下:
def testFun(**kwargs):
print(type(kwargs))
print(kwargs)
for k, v in kwargs.items():
print(k, v)
testFun(a=1, b=2, c='hello', d=['a', 'b', 'c'])
# 输出
<class 'dict'>
{'a': 1, 'b': 2, 'c': 'hello', 'd': ['a', 'b', 'c']}
a 1
b 2
c hello
d ['a', 'b', 'c']
def testFun(x, y, **kwargs):
print(kwargs)
print(x)
print(y)
testFun(1, 2, c='hello', d=[])
# 输出
{'c': 'hello', 'd': []}
1
2
注意:在书写时,参数的顺序是:(普通参数1, 普通参数2, ..., *args, **kwargs)