Python *args **kwargs

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12171406.html

 

*args

星号 * 的参数 *args 会以元组的形式导入

 1 def func(*args):
 2     for arg in args:
 3         print(arg)
 4 
 5 
 6 func('a', 'b', 'c')
 7 
 8 t = ('a', 'b', 'c')
 9 func(t)
10 
11 l = [1, 2, 3]
12 func(l)

Console Output

a
b
c
('a', 'b', 'c')
[1, 2, 3]

 

**kwargs

两个星号 ** 的参数 **kwargs 会以字典的形式导入

1 def func(**kargs):
2     for key in kargs:
3         print(key, kargs[key], type(kargs[key]))
4 
5 
6 func(k1='a', k2=[1, 2, 3], k3=(4, 5, 6))

Console Output

k1 a <class 'str'>
k2 [1, 2, 3] <class 'list'>
k3 (4, 5, 6) <class 'tuple'>

 

Reference

https://www.runoob.com/python3/python3-function.html

https://www.liaoxuefeng.com/wiki/1016959663602400/1017261630425888

posted @ 2020-01-09 14:39  李白与酒  阅读(100)  评论(0编辑  收藏  举报