📝 预计阅读时间:25 分钟 | 难度:⭐⭐⭐☆☆
🎯 学习目标
完成本课后,你将能够:
📋 课前回顾
在第 19 期中,我们学习了:
# with 语句示例
with open("data.txt", "r") as f:
content = f.read()
# 自动关闭文件
今天,我们学习 Python 3.10+ 的新特性——match case!
📚 课程内容
1. 什么是 match case?
1.1 模式匹配的本质
match case 是 Python 3.10 引入的结构化模式匹配特性,类似于其他语言的 switch-case,但更强大。
# 传统 if-elif 链
status = 404
if status == 200:
print("OK")
elif status == 404:
print("Not Found")
elif status == 500:
print("Server Error")
else:
print("Unknown")
# match case 方式(更清晰)
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Server Error")
case _:
print("Unknown")
2. match case 基础
2.1 基本语法
match 表达式:
case 模式 1:
# 代码块 1
case 模式 2:
# 代码块 2
case _:
# 默认代码块(可选)
2.2 字面量匹配
defhttp_status(status):
match status:
case 200:
return"OK"
case 404:
return"Not Found"
case 500:
return"Server Error"
case _:
return"Unknown"
print(http_status(200)) # OK
print(http_status(404)) # Not Found
3. 序列模式匹配
3.1 列表匹配
defcheck_command(command):
match command:
case ["start"]:
return"启动系统"
case ["stop"]:
return"停止系统"
case ["restart", delay]:
returnf"{delay}秒后重启"
case _:
return"未知命令"
print(check_command(["start"])) # 启动系统
print(check_command(["restart", 10])) # 10 秒后重启
3.2 元组匹配
defprocess_point(point):
match point:
case (0, 0):
return"原点"
case (x, 0):
returnf"x 轴上的点 ({x}, 0)"
case (0, y):
returnf"y 轴上的点 (0, {y})"
case (x, y):
returnf"点 ({x}, {y})"
case _:
return"无效点"
4. 字典模式匹配
defprocess_user(user):
match user:
case {"name": name, "age": age}:
returnf"{name},{age}岁"
case {"name": name}:
returnf"{name}(年龄未知)"
case _:
return"未知用户"
print(process_user({"name": "张三", "age": 25})) # 张三,25 岁
print(process_user({"name": "李四"})) # 李四(年龄未知)
5. 守卫条件
defcheck_score(score):
match score:
case s if s >= 90:
return"优秀"
case s if s >= 80:
return"良好"
case s if s >= 60:
return"及格"
case _:
return"不及格"
6. 实战:命令解析器
6.1 场景描述
创建一个命令解析器,使用 match case 处理各种用户命令。
6.2 实现代码
classCommandParser:
"""命令解析器"""
defparse(self, command):
"""解析命令"""
parts = command.strip().split()
ifnot parts:
return"请输入命令"
match parts:
case ["help"]:
return self.show_help()
case ["add", item]:
returnf"添加:{item}"
case ["add", item, quantity] if quantity.isdigit():
returnf"添加{quantity}个{item}"
case ["remove", item]:
returnf"删除:{item}"
case ["list"]:
return"显示列表"
case ["search", keyword]:
returnf"搜索:{keyword}"
case ["exit" | "quit"]:
return"退出系统"
case _:
returnf"未知命令:{command}"
defshow_help(self):
"""显示帮助"""
return"""
可用命令:
help - 显示帮助
add <物品> - 添加物品
add <物品> <数量> - 添加指定数量的物品
remove <物品> - 删除物品
list - 显示列表
search <关键词> - 搜索
exit/quit - 退出
"""
# 测试
parser = CommandParser()
commands = [
"help",
"add 苹果",
"add 香蕉 5",
"remove 橙子",
"list",
"search 苹果",
"exit",
"unknown",
]
for cmd in commands:
print(f"> {cmd}")
print(f" {parser.parse(cmd)}\n")
📝 课后练习
练习 1:HTTP 状态码
# 根据 HTTP 状态码返回描述
defhttp_status(status):
pass
print(http_status(200)) # OK
print(http_status(404)) # Not Found
练习 2:形状面积计算
# 根据形状计算面积
defcalculate_area(shape):
pass
print(calculate_area(("circle", 5))) # 圆,半径 5
print(calculate_area(("rect", 4, 5))) # 矩形,4×5
练习 3:数据类型判断
# 使用 match case 判断数据类型
defcheck_type(value):
pass
📚 总结
核心知识点
| |
|---|
| match 表达式: |
| |
| |
| |
| case x if 条件: |
| case _: |
🚀 下一步
第 22 期:assert——断言调试利器!