-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatch.py
More file actions
58 lines (47 loc) · 1.38 KB
/
match.py
File metadata and controls
58 lines (47 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
status = 404
match status:
case 200:
print("请求成功")
case 400:
print("错误请求")
case 404:
print("页面未找到")
case _:
# 下划线 _ 表示 "其他所有情况",类似于 switch 中的 default
print("未知状态")
point = (0, 10)
match point:
case (0, 0):
print("原点")
case (0, y):
# 匹配 x 为 0,并将第二个元素赋值给变量 y
print(f"在 Y 轴上,Y={y}")
case (x, 0):
# 匹配 y 为 0,并将第一个元素赋值给变量 x
print(f"在 X 轴上,X={x}")
case (x, y):
print(f"坐标点在 ({x}, {y})")
case _:
print("这不是一个二维坐标")
user = {"name": "Alice", "role": "admin", "id": 123}
match user:
case {"role": "admin"}:
# 只要字典里有 role: admin 这一项就匹配
print("这是一个管理员")
case {"role": "guest", "name": name}:
# 匹配 role 是 guest,并把 name 的值提取出来
print(f"访客姓名: {name}")
case _:
print("权限不足或未知用户")
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
pt = Point(1, 5)
match pt:
case Point(x=0, y=0):
print("对象在原点")
case Point(x=x, y=y):
# 匹配是 Point 类型,并提取属性
print(f"Point 对象: x={x}, y={y}")