目录
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 = 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)
运行效果如下:
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","man"))
func(["John","female"])
运行效果如下:
可以看到,我们在调用时有两个参数的方式、三个参数的方式,限定参数内容的方式和不限定参数的方式,甚至通配的方式,函数都能够畅快的运行。
我们在示例中有使用了元组方式和列表方式作为参数,但其实我们可以使用任何可迭代对象。