Python 3.10 尝鲜

Python 3.10 尝鲜

image-20211024175520787

图源:giaiphapso.com

Python 3.10 版本已经在本月初(10.4)正式发布,其中最让人振奋的新特性是模式匹配,简单的说就是Python终于引入了类似于switch...case的语句,当然实际功能和效果要比那个强大的多。

下面就是我迟来的Python 3.10尝鲜报告。

下载&&安装

3.10版的官方下载地址是这里

image-20211024171711034

选择需要的版本就好,我下载的是Windows installer (64-bit)

image-20211024171915596

安装包推荐自定义安装,这里我选择安装的目录是之前安装的3.9版本的目录,进行覆盖安装。

通过命令行验证安装成功:

❯ python --version
Python 3.10.0

模式匹配

3.10最显著的新特性是模式匹配,这点在知乎有很多人讨论,该功能相关的PEP有三个:

  • PEP 634 – Structural Pattern Matching: Specification
  • PEP 635 – Structural Pattern Matching: Motivation and Rationale
  • PEP 636 – Structural Pattern Matching: Tutorial

其中PEP-634是模式匹配语法的完整规范,PEP-635是解释为什么需要引入模式匹配,PEP-636是模式匹配的新手教程。用整整三篇PEP来阐述一个新特性,可见其重要性和社区的期待。

我已经翻译了其中的PEP-634和PEP-636,译文见:

  • [PEP 634 – Structural Pattern Matching: Specification](https://github.com/icexmoon/PEP-CN/blob/main/peps/PEP 634 – Structural Pattern Matching Specification.md),结构化模式匹配:规范
  • [PEP 636 – Structural Pattern Matching: Tutorial](https://github.com/icexmoon/PEP-CN/blob/main/peps/PEP 636 – Structural Pattern Matching Tutorial.md),结构化模式匹配:教程

如果访问Github不便,推荐使用**dev-sidecar**或访问该PEP翻译项目在Gitee上的镜像PEP-CN

现在啥也不说了,直接撸代码试试。

先来试试最常见的switch...case式的代码:


def player_test(player):
    match player:
        case 'customer':
            print('you are a customer player')
        case 'icexmoon':
            print('you are god')
        case _:
            print('you are a hacker')

player_test('icexmoon')
player_test('xiao min')
player_test('customer')
# you are god
# you are a hacker
# you are a customer player

非常简洁,不需要写breakdefault,当然,不要忘记在结尾写case _

当然,对于模式匹配来说这只是小case,其能做的远远超过普通的switch...case

比如直接匹配序列,并捕获其中的变量:

persons = [['Xiao Ming',16],
           ['Han Meimei', 20],
           ['Li Xiang', 15]]
for person in persons:
    match person:
        case 'Li Xiang', age:
            print("The boy's name is Li Xiang, and his age is {}".format(age))
        case name, age:
            print("{}'s age is {}".format(name, age))
        case _:
            pass
# Xiao Ming's age is 16
# Han Meimei's age is 20
# The boy's name is Li Xiang, and his age is 15

在这个例子中我们通过模式匹配捕获二维列表中的人名和年龄,并且对其中Li Xiang进行特殊对待,输出与其他人不同的信息。

当然模式匹配还有更多的功能,这里不一一展示,详情请见前边列出的相关PEP。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值