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>

运行效果如下:

d3a9e87b7d2181b0aec9eb4d754435b5.png

可以看到,如果能匹配到,就返回对应的语句,否则就返回最后一行的通配语句。当然,统配语句也可以省略,省略相当于返回 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")

运行效果如下:

635b0b86dfa4c767cfdc0b6c45ee07af.png

03 类(class)

class Point():
    def __init__(self,x,y):
        self.x = x
        self.y = y
 
def 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)

运行效果如下:

2e795cb9b9e9f92d3ccaf0279017d62b.png

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.")

运行效果如下:

5a3e91deabce985415b98c6fa4835205.png

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","man"))
func(["John","female"])

运行效果如下:

220f22b18f019f5e45875369ef377012.png

可以看到,我们在调用时有两个参数的方式、三个参数的方式,限定参数内容的方式和不限定参数的方式,甚至通配的方式,函数都能够畅快的运行。

我们在示例中有使用了元组方式和列表方式作为参数,但其实我们可以使用任何可迭代对象。

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...