版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
<!--一个博主专栏付费入口结束-->
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-4a3473df85.css">
<div id="content_views" class="markdown_views prism-atom-one-dark">
<!-- flowchart 箭头图标 勿删 -->
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
</svg>
<p>*args和**kwargs常用来函数的参数传递上:</p>
def f(x, *args, **kwargs):
print(type(x), x)
print(type(args), args)
print(type(kwargs), kwargs)
f(1,2,3, a=1, b=2)
- 1
- 2
- 3
- 4
- 5
- 6
输出:
<class 'int'> 1
<class 'tuple'> (2, 3)
<class 'dict'> {'a': 1, 'b': 2}
- 1
- 2
- 3
x为自定义的变量值,接收第一个值,args接收剩余的值并通过*汇聚成一个tuple;kwargs接收剩余的键值对并通过 ** 汇聚成一个字典。上述的3部分顺序是不能颠倒的,前两部分称为位置参数,最后一部分属于关键字参数。
在函数定义时,*和**的作用是汇聚参数为tuple和dict,但是在参数传递的时候相当于分解参数。
*list,tuple:可以将列表,元组拆分为多个元素
**dict:可以将字典分解为独立的元素。此时键值为变量名,对应的值就是变量的值。
def add(a, b):
return a - b
data = [4, 3]
print(add(data)) # 1, 等价于add(4,3)
print(data) # 4 3
data = {‘a’: 4, ‘b’: 3}
print(add(data)) # 1,等价于add(a=4, b=3)
data = {‘a’: 3, ‘b’: 4}
print(add(data)) # -1,等价于add(a=3,b=4)
print(**data) # 无法直接输出
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
可以通过使用**灵活地汇聚参数和分解参数:
def add(a, b):
return a+b
def f(x, kwargs):
print(x)
print(kwargs) # {‘a’: 1, ‘b’: 2}
print(add(kwargs)) # add(a=1, b=2)
f(1, a=1, b=2)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-b6c3c6d139.css" rel="stylesheet">
</div>