Python中*和**的区别
2024-08-23 05:20:35
Python中,(*)会把接收到的参数形成一个元组,而(**)则会把接收到的参数存入一个字典
我们可以看到,foo方法可以接收任意长度的参数,并把它们存入一个元组中
>>> def foo(*args):
... print(args)
...
>>> foo("fruit", "animal", "human")
('fruit', 'animal', 'human')
>>> foo(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5)
>>> arr = [1, 2, 3, 4, 5] # 如果我们希望将一个数组形成元组,需要在传入参数的前面 加上一个*
>>> foo(arr)
([1, 2, 3, 4, 5],)
>>> foo(*arr)
(1, 2, 3, 4, 5)
(**)将接收到的参数存入一个字典
>>> def foo(**kwargs):
... for key, value in kwargs.items():
... print("%s=%s" % (key, value))
...
>>> foo(a=1, b=2, c=3)
a=1
b=2
c=3
(*)和(**)一起使用
>>> def foo(*args, **kwargs):
... print("args:", args)
... print("kwargs:", kwargs)
...
>>> foo(1, 2, 3, a=1, b=2)
args: (1, 2, 3)
kwargs: {'a': 1, 'b': 2}
>>> arr = [1, 2, 3]
>>> foo(*arr, a=1, b=2)
args: (1, 2, 3)
kwargs: {'a': 1, 'b': 2}
name作为foo第一个参数,在调用foo("hello", 1, 2, 3, middle="world", a=1, b=2, c=3)方法时,自然而然捕获了hello,而middle必须经过指定关键字参数才可以捕获值,否则会和之前的参数一样形成一个元组
>>> def foo(name, *args, middle=None, **kwargs):
... print("name:", name)
... print("args:", args)
... print("middle:", middle)
... print("kwargs:", kwargs)
...
>>> foo("hello", 1, 2, 3, a=1, b=2, c=3)
name: hello
args: (1, 2, 3)
middle: None
kwargs: {'a': 1, 'b': 2, 'c': 3}
>>> foo("hello", 1, 2, 3, middle="world", a=1, b=2, c=3)
name: hello
args: (1, 2, 3)
middle: world
kwargs: {'a': 1, 'b': 2, 'c': 3}
>>> my_foo = {"name": "hello", "middle": "world", "a": "1", "b": "2", "c": "3"}
>>> foo(**my_foo)
name: hello
args: ()
middle: world
kwargs: {'a': '1', 'b': '2', 'c': '3'}
此外,我们还可以定义一个字典my_foo,并以foo(**my_foo)这样的方式,让name和middle各自捕获自己的值,没有捕获的则存入一个字典
当我们删除my_foo中的name,再像之前传入函数,函数会报错说需要name这个参数
>>> del my_foo["name"]
>>> foo(**my_foo)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'name'
最新文章
- MVC系列——MVC源码学习:打造自己的MVC框架(一:核心原理)
- Delphi的 Format格式化函数
- 第一次在Django上编写静态网页
- 《CODE》读后笔记——第21~25章
- 疯狂java学习笔记之面向对象(二) - 成员变量与局部变量
- workon在zsh中不起作用
- Bmob用户管理操作
- 如何在 Linux 中找出最近或今天被修改的文件
- Channel Allocation(DFS)
- win10 UWP GET Post
- 从壹开始前后端分离 [ vue + .netcore 补充教程 ] 二八║ Nuxt 基础:面向源码研究Nuxt.js
- js单元测试
- C#后台接java接口传输字节数组(byte[])
- LeetCode算法题-Min Stack(Java实现)
- jenkins 邮箱设置
- NodeJS对象数组Array 根据对象object key的值排序sort
- 生成、查看文件的MD5、SHA、SHA256值
- Jmeter-使用Stepping Thread Group插件来设置负载场景
- 寻路优化(二)——二维地图上theta*算法的设计探索
- TVS二极管和稳压二极管的区别
热门文章
- 命名空间namespace、smarty使用(视图分离,MVC)、smarty模板语法、smarty缓存、MVC模式
- socket网络套节字---聊天室
- eCharts图表(polar极坐标图)
- jq动态增加的button标签click回调失效的问题,即动态增加的button标签绑定事件$(";button.class";).click(function)无效
- WPS去掉英语单词下面的红斜线
- yii2 详细分解实现分页效果
- CAsyncSocket create创建套接字失败
- World Wind Java开发之二 使用Winbuilders设计图形用户界面(转)
- Aizu 2304 Reverse Roads(无向流)
- Spark性能优化——和shuffle搏斗