python 3.10 新增 switch-case 简介
目录
01 通用语法
02 在元组中运用
03 类(class)
04 if 子句模式
05 复杂模式和通配符
01 通用语法
Switch 语句存在于很多编程语言中,早在 2016 年,PEP 3103 就被提出,建议 Python 支持 switch-case 语句。
时间在推到 2020 年,Python的创始人Guido van Rossum,提交了显示 switch 语句的第一个文档,命名为 Structural Pattern Matching。
如今,随着 Python 3.10 beta 版的发布,终于将 switch-case 语句纳入其中。
在 Python 中,这一功能由 match 关键词和 case 语句组成。
通用语法如下:
match subject:case <pattern_1>:<action_1>case <pattern_2>:<action_2>case <pattern_3>:<action_3>case _:<action_wildcard>
运行效果如下:
可以看到,如果能匹配到,就返回对应的语句,否则就返回最后一行的通配语句。当然,统配语句也可以省略,省略相当于返回 None.
另外,case 455 | 456:
这行语句中的 |
(逻辑or
操作符)可以组合多个选项。
02 在元组中运用
point=(5,6)
match point:case (0, 0):print("Origin")case (0, y):print(f"Y={y}")case (x, 0):print(f"X={x}")case (x, y):print(f"X={x}, Y={y}")case _:raise ValueError("Not a point")
运行效果如下:
03 类(class)
class Point():def __init__(self,x,y):self.x = xself.y = ydef location(point):match point:case Point(x=0, y=0):print("Origin is the point's location.")case Point(x=0, y=y):print(f"Y={y} and the point is on the y-axis.")case Point(x=x, y=0):print(f"X={x} and the point is on the x-axis.")case Point():print("The point is located somewhere else on the plane.")case _:print("Not a point")point = Point(0, 1)
location(point)
运行效果如下:
04 if 子句模式
我们可以 if 在模式中添加一个子句,称为 “Guard”(警卫、守卫 的意思)。如果 Guard 是错误的,match 则继续尝试下一个 case 块。
我们先写一个例子:
point = Point(x=0,y=0)
match point:case Point(x=x, y=y) if x == y:print(f"The point is located on the diagonal Y=X at {x}.")case Point(x=x, y=y):print(f"Point is not on the diagonal.")
运行效果如下:
05 复杂模式和通配符
下面是一个复杂模式的例子,我们先来看看代码:
def func(person):match person:case (name,"teacher"):print(f"{name} is a teacher.")case (name, _, "male"):print(f"{name} is man.")case (name, _, "female"):print(f"{name} is woman.")case (name, age, gender):print(f"{name} is {age} old.")func(("Sam", "teacher"))
func(("John", 25, "male"))
func(("John", 25, "man"))
func(["John", 25, "female"])
运行效果如下:
可以看到,我们在调用时有两个参数的方式、三个参数的方式,限定参数内容的方式和不限定参数的方式,甚至通配的方式,函数都能够畅快的运行。
我们在示例中有使用了元组方式和列表方式作为参数,但其实我们可以使用任何可迭代对象。
python 3.10 新增 switch-case 简介相关推荐
- Python 3.10新增软关键字实现真正意义上的多分支选择结构
推荐教材: <Python程序设计基础与应用(第2版)>(微课版)(ISBN:978-7-111-69670-4),机械工业出版社,2022年1月出版.面向新工科高等院校大数据专业系列教材 ...
- python中case的用法_用 Python 实现简单的 switch/case 语句
在Python中是没有Switch / Case语句的,很多人认为这种语句不够优雅灵活,在Python中用字典来处理多条件匹配问题字典会更简单高效,对于有一定经验的Python玩家不得不承认,的确如此 ...
- python中case的用法_python中Switch/Case实现的示例代码
python 的 python中Switch/Case实现的示例代码 学习Python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现 ...
- python中有没有switch_Python为什么没有switch/case语句?
与我之前使用的所有语言都不同,Python没有switch/case语句.为了达到这种分支语句的效果,一般方法是使用字典映射: def numbers_to_strings(argument): sw ...
- python中没有switch-case_Python为什么没有switch/case语句?
与我之前使用的所有语言都不同,Python没有switch/case语句.为了达到这种分支语句的效果,一般方法是使用字典映射: def numbers_to_strings(argument): sw ...
- python中有没有switch_为什么python没有switch/case
为什么python没有switch/case 不同于其他编程语言,python中是没有switch/case 这种语法的,如果你是从其他语言转到python的,期初,对于没有switch/case 是 ...
- Java修饰符、Java运算符、Java循环语句、Java条件语句、Java switch case
Java 修饰符 Java语言提供了很多修饰符,主要分为以下两类: 访问修饰符 非访问修饰符 修饰符用来定义类.方法或者变量,通常放在语句的最前端.我们通过下面的例子来说明: public class ...
- Python 3.10 正式发布,新增模式匹配,同事用了直呼真香
关注微信公众号:K哥爬虫,QQ交流群:808574309,持续分享爬虫进阶.JS/安卓逆向等技术干货! 前言 前几天,也就是 10 月 4 日,Python 发布了 3.10.0 版本,什么?3.9 ...
- Python 3.10来了,switch语法终于出现
开发者(KaiFaX) 面向全栈工程师的开发者专注于前端.Java/Python/Go/PHP的技术社区 来源:机器之心 正文 不用再自己琢磨如何实现 switch 功能了. 对于从事数据科学和人工智 ...
最新文章
- Vi非正常退出导致敏感信息泄露
- 图灵2010.10书讯
- ACM - 算法篇,基础题目
- Java内存图以及堆、栈、常量区、静态区、方法区的区别
- Docker 升级 npm v3 报错 cross-device link not permitted, rename
- 计算机二级考试需要怎么备考,计算机二级ms office应该怎么备考 考试内容是什么...
- 有些事情现在不做一辈子就都不会做了
- 循环序列模型 —— 1.1 为什么选择序列模型
- 处理接口超时_架构设计 | 接口幂等性原则,防重复提交Token管理
- LEARNING PYTORCH WITH EXAMPLES
- 32乘法运算_算术运算指令
- 洛谷——P1720 月落乌啼算钱(斐波那契数列)
- 有专用DHCP服务器的网络的简单配置
- 超详细图文介绍,华为桌面云解决方案
- 002 如何将电子版一寸照以照片的方式打印出来
- 无人驾驶路径规划之RRT算法
- 微信公众号H5支付的两种方式
- Gallery与Imageswitch完美结合 做相册一绝啊
- 【仿真建模】第四课:AnyLogic入门基础课程 - 轨道交通仿真入门讲解
- [笔记]-后端学习笔记