条件判断
if
if xxxx:
pass
elif xxxx:
pass
else:
pass
xxxx
是一个表达式,并且这个表达式可以被转换为布尔值
策略模式
python 3.10 前没有
switch-case
的语法, 官方推荐通过字典+get来完成
plus = lambda x,y: x + y
minus = lambda x,y: x - y
times = lambda x,y: x * y
divide = lambda x,y: x / y
op = {
'+': plus,
'-': minus,
'*': times,
'/': divide
}
def f(x, o, y):
return op.get(o)(x, y)
match-case
python 3.10 推出的新特性,类似于 switch-case
match
语句将 subject
表达式 与 case
语句中的每个模式(pattern)从上到下进行比较,直到找到匹配的模式。
若找不到匹配的表达式,则匹配 _
通配符(wildcard)
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
特点:
- 无需
break
关键字- python 在匹配成功后就停止,所以不能在每个
case
结尾写break
(如果写了会抛出SyntaxError
) - 如何堆叠多个
case
- python 在匹配成功后就停止,所以不能在每个
switch (status) {
case 401:
case 402:
print('error')
break
default:
print('success')
}
使用 |
来结合多个模式(模式匹配中唯一支持的运算符)
match status:
case 401 | 402:
print('error')
case _:
print('success')
- 序列可以作为模式,配合
*
、**
和_
使用[*_]
匹配任意长度的list
(_, _, *_)
匹配长度至少为 2 的tuple
- 类模式
Sandwich(cheese=_)
检查匹配的Sandwich
对象是否具有属性cheese
class Point:
x: int
y: int
def location(point):
match point:
case Point(x=0, y=0):
print("Origin is the point's location.")
case Point(x=0, y=y):
print(f"Y={y} and the point is on the y-axis.")
case Point(x=x, y=0):
print(f"X={x} and the point is on the x-axis.")
case Point():
print("The point is located somewhere else on the plane.")
case _:
print("Not a point")
- 可以在模式中添加一个
if
语句,称为 guard(守卫)。即使模式匹配,如果 guard 为False
,match
将继续尝试匹配下一个case
块
match point:
case Point(x, y) if x == y:
print(f"The point is located on the diagonal Y=X at {x}.")
case Point(x, y):
print(f"Point is not on the diagonal.")