
match-case 是 Python 3.10 引入的一种结构化的模式匹配 语法,功能类似于其他语言中的 switch-case,但远比它强大和灵活 。它不仅仅是值的匹配,而是基于结构的匹配。
一、基本语法:值的匹配
最简单的用法就是匹配一个变量的值。
def http_status(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown Status"
print(http_status(404)) # Not Found
这里的 _ 是通配符,匹配所有未被前面 case 捕获的情况(类似于其他语言的 default)。
二、匹配字面量、变量和类型
1. 匹配多个值(使用 | 表示或)
def get_weekday(num):
match num:
case 1 | 7:
return "周末"
case 2 | 3 | 4 | 5 | 6:
return "工作日"
case _:
return "无效数字"
2. 匹配变量,并捕获值
可以用 case 中的变量来"捕获"匹配到的值,供后续使用。注意:变量名必须是大写 (如 CODE),否则会和通配符混淆(但实际规则更细一些)。
def handle_code(code):
match code:
case 200:
print("成功")
case CODE: # 这里匹配任意值,并赋值给 CODE
print(f"未知状态码: {CODE}")
3. 匹配类型(使用 case 配合 isinstance 的语法糖)
注意:这里不是直接写类名,而是使用"类模式",写法类似构造函数。
def process_value(value):
match value:
case int():
print("这是一个整数")
case str():
print("这是一个字符串")
case list():
print("这是一个列表")
case _:
print("其他类型")
三、解构模式
这是 match-case 真正强大的地方:可以解构数据,匹配内部结构并提取数据。
1. 匹配序列(列表/元组)
def process_point(point):
match point:
case [0, 0]:
print("原点")
case [x, 0]:
print(f"在 X 轴上,x={x}")
case [0, y]:
print(f"在 Y 轴上,y={y}")
case [x, y]:
print(f"普通点,x={x}, y={y}")
case _:
print("不是二维点")
process_point([0, 5]) # 在 Y 轴上,y=5
2. 匹配字典
def handle_json(data):
match data:
case {"type": "user", "name": name, "age": age}:
print(f"用户: {name}, 年龄: {age}")
case {"type": "product", "name": name, "price": price}:
print(f"产品: {name}, 价格: {price}")
case _:
print("未知数据结构")
3. 匹配对象(类实例)
class Point:
__match_args__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
def process_point(p):
match p:
case Point(x=0, y=0):
print("原点")
case Point(x=x, y=0):
print(f"在X轴上, x={x}")
case Point(x=0, y=y):
print(f"在Y轴上, y={y}")
case Point(x=x, y=y):
print(f"普通点, x={x}, y={y}")
四、与 switch-case 的区别
match-case 和传统的 switch-case 看起来像,但本质不同:
| 特性 | match-case |
传统 switch-case |
|---|---|---|
| 支持解构 | 是 | 否 |
| 匹配类型 | 支持 | 不支持 |
| 通配符 | _ |
default |
| 多值匹配 | `case 1 | 2` |
| 匹配模式 | 模式匹配 | 值匹配 |