不用再自己琢磨如何实现 switch 功能了。
对于从事数据科学和人工智能领域的人们来说,Python 是大家的首选编程语言。
根据最近的一项调查,27% 的程序员开发职位要求掌握 Python 语言,今年年初这一数字还只是 18.5%。
Python 流行的原因在于其拥有非常直观的能力:这门语言拥有大量的库、足够高的生产效率,还易于学习。2021年6月9号,Python官方发布了3.10的新功能介绍:
以往,开发者看到新版本时就会暗暗叫苦,因为又要学习新功能、新特性,可能还要修改程序,但这次的更新却引来了一致好评。
Python 3.10 不但加入了建议已久的 switch-case 语句,还优化了报错提示、缩进提醒等问题。预计用不了多久,Python 就能摆脱“游标卡尺语言”这个梗了。
今天,就给大家详细介绍一下 Python 3.10 的 switch-case 特性和进阶玩法。
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", 25, "man"))
func(["John", 25, "female"])
运行效果如下:
可以看到,我们在调用时有两个参数的方式、三个参数的方式,限定参数内容的方式和不限定参数的方式,甚至通配的方式,函数都能够畅快的运行。
我们在示例中有使用了元组方式和列表方式作为参数,但其实我们可以使用任何可迭代对象。
06
总结
Python 3.10 的 match..case 功能也可以算是一大改进,这篇文章带大家学习了 match..case 的方法和技巧。