python-match statement

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值