红茶的个人站点

  • 首页
  • 专栏
  • 开发工具
  • 其它
  • 隐私政策
Awalon
Talk is cheap,show me the code.
  1. 首页
  2. 编程语言
  3. Python
  4. 正文

Python 3.10 尝鲜

2021年10月24日 1199点热度 0人点赞 0条评论

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,结构化模式匹配:规范

  • PEP 636 -- Structural Pattern Matching: Tutorial,结构化模式匹配:教程

如果访问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

非常简洁,不需要写break和default,当然,不要忘记在结尾写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。

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: Python
最后更新:2021年10月24日

魔芋红茶

加一点PHP,加一点Go,加一点Python......

点赞
< 上一篇
下一篇 >

文章评论

取消回复

*

code

COPYRIGHT © 2021 icexmoon.cn. ALL RIGHTS RESERVED.
本网站由提供CDN加速/云存储服务

Theme Kratos Made By Seaton Jiang

宁ICP备2021001508号

宁公网安备64040202000141号