洋洋涵

模式匹配

match ... case 是 Python 3.10 中引入的一个新特性,也被称为“模式匹配”或“结构化匹配”。

它为 Python 带来了更强大、更易读的分支控制,相比于传统的 if-elif-else 链。

基本模式匹配

x = 10
match x:
    case 10:
        print("x is 10")
    case 20:
        print("x is 20")
    case _:
        print("x is something else")

在这里,_是一个特殊的“占位符”模式,用于匹配任何值(类似于 else)。

序列模式匹配

point = (2, 3)
match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Point is on the Y axis at {y}")
    case (x, 0):
        print(f"Point is on the X axis at {x}")
    case (x, y):
        print(f"Point is at ({x}, {y})")
    case _:
        print("Not a point")

对象模式匹配

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(0, 3)
match p:
    case Point(x=0, y=y):
        print(f"Point is on the Y axis at {y}")
    case Point(x=x, y=0):
        print(f"Point is on the X axis at {x}")
    case Point(x, y):
        print(f"Point is at ({x}, {y})")
    case _:
        print("Not a point")

OR 模式

使用 | 来表示一个或多个模式。

x = 2
match x:
    case 1 | 2 | 3:
        print("x is 1, 2, or 3")
    case _:
        print("x is something else")

守卫

你可以使用 if 在模式匹配中添加额外的条件。

x = 10
match x:
    case x if x > 5:
        print("x is greater than 5")
    case _:
        print("x is 5 or less")