python中的match语句,与java中的Switch语句相似,但也有差别
def http_error(status):
match status:
case 400:
return "Bad Request"
case 404:
return "Not Found"
case 418:
return "I'm a teapot"
case _:
# 类似java中Switch语句中default分支
return "Something's wrong with the internet"
print(http_error(418))
print(http_error(500))
输出:
I'm a teapot
Something's wrong with the internet
一个case匹配多个,用 |(or关系)
def http_error(status):
match status:
case 401 | 403 | 404: # 多个同时匹配
return "Not allowed"
case _:
return "unkown"
print(http_error(404))
print(http_error(200))
输出:
Not allowed
unkown
def where_is(point):
match point: # point is an (x, y) tuple
case (0, 0): # 两个字面常量
print("Origin")
case (0, y): # 一个字面常量,一个变量
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y): # 两个变量,概念上类似于(x, y) = point
print(f"X={x},Y={y}")
case _:
raise ValueError("Not a point")
where_is((0, 0))
where_is((0, 11))
where_is((22, 0))
where_is((33, 44))
输出:
Origin
Y=11
X=22
X=33,Y=44
如果您正在使用class来构建数据,您可以使用伴随有参数列表的类名称,类似于构造函数。将属性捕获到变量中
class Point:
x: int
y: int
def where_is(point):
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print(f"Y={y}")
case Point(x=x, y=0):
print(f"X={x}")
case Point():
print("Somewhere else")
case _:
print("Not a point")
case匹配可以使用命名常量。必须使用.name
格式,以防止它们被解释为捕获变量
from enum import Enum
class Color(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
color = Color(input("Enter your choice of 'red','blue' or 'green':"))
match color:
case Color.RED:
print("I see red!")
case Color.GREEN:
print("Grass is green")
case Color.BLUE:
print("I'm feeling the blues:(")
输出:
Enter your choice of 'red','blue' or 'green':green
Grass is green