Skip to content

匹配语句(Match Statement)

一句话解释

match/case 是 Python 的模式匹配(3.10+)——类似 switch/case 但带解构、类型检查和守卫。

用大白话说

match 语句(Python 3.10+,PEP 634)是结构化模式匹配。它远比简单的 switch/case 强大:1. 字面量匹配——case 1:、case "hello":

  1. 变量绑定——case [x, y]: 解包并绑定 x、y
  2. 类型匹配——case Point(x, y): 匹配类实例
  3. 守卫——case [x, y] if x > y: 添加条件
  4. 通配符——case _: 匹配任何东西(默认)

模式从上到下检查;第一个匹配获胜。_ 通配符必须最后。这用更清晰、更可读的代码替代冗长的 if/elif 链。

示例

python
def handle_command(cmd):
    match cmd.split():
        case ["quit"]:
            return "Exiting"
        case ["hello", name]:
            return f"Hi {name}"
        case ["move", x, y]:
            return f"Moving to {x}, {y}"
        case ["search", *keywords]:  # * captures rest
            return f"Searching: {keywords}"
        case _:
            return "Unknown command"

print(handle_command("hello Alice"))    # Hi Alice
print(handle_command("move 10 20"))    # Moving to 10, 20
print(handle_command("search py js"))  # Searching: ['py', 'js']

# Type matching with classes
class Point:
    def __init__(self, x, y):
        self.x = x; self.y = y

match Point(1, 2):
    case Point(x=0, y=0):
        print("origin")
    case Point(x=x, y=y):
        print(f"point at {x},{y}")

match/case 支持字面量、解包、通配符(*)和守卫。远比 switch/case 强大——它是结构化模式匹配。

常见混淆

  • 容易混淆的对象: if/elif

    关键区别: match/case 做结构化模式匹配——它可以解构、绑定变量并匹配类型/形状,而非仅比较值。if/elif 只评估布尔表达式。复杂数据分派用 match 更声明式更强大,但基本条件用 if/elif 更简单。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表