Python 3.10引入match语句实现模式匹配,支持字面量、变量、结构、类实例等多种模式,可结合守卫条件和OR模式进行灵活匹配,按顺序执行首个匹配分支,提升处理结构化数据的代码可读性。

Python 3.10 引入了 match 语句,这是 Python 首次原生支持模式匹配(Pattern Matching),类似于其他语言中的“switch”语句,但功能更强大。它不仅支持简单的值比较,还能解构数据结构、绑定变量、进行类型检查等。
基本语法结构
match 语的基本形式如下:
match subject:
case pattern1:
action1
case pattern2:
action2
...
case _:
default_action
其中:
- subject 是要匹配的值。
- case 后面是模式(pattern),用于尝试匹配 subject。
- 模式从上到下依次尝试,第一个匹配成功的分支执行对应代码。
- _ 是通配符模式,表示“匹配任何值”,常用于默认分支。
常见模式类型
match 支持多种模式,可以灵活组合使用。
立即学习“Python免费学习笔记(深入)”;
1. 字面量模式(Literal Patterns)
匹配具体的值,如数字、字符串、True、False、None 等。
match status:
case 400:
print("Bad request")
case 404:
print("Not found")
case 500:
print("Server error")
case _:
print("Unknown status")
2. 变量模式与通配符
单独一个名称会捕获该值并绑定到变量;_ 不绑定任何变量。
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y-axis at y={y}")
case (x, 0):
print(f"X-axis at x={x}")
case (x, y):
print(f"Point at ({x}, {y})")
注意:只有 _ 不会被当作变量绑定,其他字母都会创建或覆盖变量。
3. 结构模式(Sequence、Mapping)
可匹配列表、元组、字典等结构。
# 匹配元组结构
match command.split():
case ["quit"]:
print("Goodbye!")
case ["move", direction]:
print(f"Moving {direction}")
case ["attack", target]:
print(f"Attacking {target}")
匹配列表(支持可变长度)
match items:
case [first, *rest]:
print(f"First: {first}, Rest: {rest}")
case []:
print("Empty list")
匹配字典
match user:
case {"name": name, "age": age}:
print(f"User: {name}, Age: {age}")
4. 类实例模式
可用于匹配类的实例,并提取其属性。
class Point:
__match_args__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
match point:
case Point(0, 0):
print("Origin")
case Point(x, y) if x == y:
print(f"Lies on line y=x at ({x}, {y})")
case Point(x, y):
print(f"Point at ({x}, {y})")
注意:__match_args__ 定义了解构顺序,方便位置参数匹配。
5. 条件守卫(Guard)
在 case 后使用 if 添加额外条件。
match point:
case (x, y) if x > 0 and y > 0:
print("First quadrant")
case (x, y) if x < 0 and y > 0:
print("Second quadrant")
case _:
print("Other quadrants")
守卫条件必须为真才算匹配成功。
6. 多重模式(OR 模式)
使用 | 表示多个模式任一匹配即可。
match value:
case int() | float() if value > 0:
print("Positive number")
case str() | list() if len(value) == 0:
print("Empty sequence")
注意:带守卫的 OR 模式中,守卫适用于整个组合。
注意事项与最佳实践
使用 match 语句时需注意以下几点:
- 模式匹配是**顺序优先**的,先匹配到的 case 执行后不再检查后续。
- 尽量将具体模式放在前面,通用模式(如变量或 _)放后面。
- 避免在模式中使用可变对象字面量(如 [1,2,3] 是允许的,但不推荐用于复杂场景)。
- match 不支持任意表达式作为模式,只能使用特定的模式语法。
- 对于简单枚举或整数选择,match 比 if-elif 更清晰;对于复杂逻辑仍建议用传统控制流。
基本上就这些。match 语句让 Python 在处理结构化数据和状态分发时更加简洁直观,合理使用能显著提升代码可读性。虽然功能强大,但也别过度设计模式,保持代码清晰最重要。









