python3.10-一些有意思的语法

python3.10发行已经有一段时间了,但是时至今日才开始用上python3.10版本,说实话有点惭愧。下面来记录一下,在Python3.10版本中几个亮眼的语法变更:

带括号的上下文管理器

在以前,我们如果需要打开多个文件,我们通常会使用多个with操作,就像这样:

with open("a.txt", "r") as fa:
    pass
    
with open("b.txt", "w") as fb:
    pass

在python3.10中,引入了带括号的上下文管理器,我们可以这样写了:

with (
    open("a.txt", "r") as fa,
    open("b.txt", "w") as fb
):
    pass

结构模式匹配

结构模式匹配已以match语句 和具有关联操作的模式的case 语句的形式添加。模式由序列、映射、原始数据类型以及类实例组成。模式匹配使程序能够从复杂的数据类型中提取信息,在数据结构上进行分支,并根据不同形式的数据应用特定的操作。如下:

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

你还可以使用|将多个条件组合在一个模式中:

case 401 | 403 | 404:
    return "Not Allowed"

如果未使用case _匹配,并且上面的case条件都不满足的情况下,将会发生空操作,即返回一个None

用于match匹配的变量,除了数字或字符串之外,还可以是一个元组或者列表,甚至是一个类的对象。使用如下:

  • 元组
def location(points):
    match points:
        case (0, 1):
            print("(0, 1) is the point's location.")
        case (1, 0):
            print("(1, 0) is the point's location.")
        case _:
            print("other")
            
if __name__ == "__main__":
    location((0, 1))        # (0, 1) is the point's location.
    location((1, 0))        # (1, 0) is the point's location.
    location((1, 1))        # other
  • 列表
def match_case(var):
    match var:
        case []:
            print("var is empty")
        case [1, 2]:
            print("var is [1, 2]")
        case [1, 1]:
            print("var is [1, 1]")
        case _:
            print("other")

if __name__ == "__main__":
    match_case([])          # var is empty
    match_case([1, 2])      # var is [1, 2]
    match_case([1, 1])      # var is [1, 1]
    match_case([2, 2])      # other
  • 类对象
class Point(object):
    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):   # x为0,y为任一值
            print(f"Y={y} and the point is on the y-axis")
        case Point(x=x, y=0):   # y为0,x为任一值
            print(f"X={x} and the point is on the x-axis")
        case Point():           # x或y没有值,或都没有值的情况
            print("The point is located somewhere else on the plane.")
        case _:
            print('not a plane')
  • 通配符
match test_variable:
    case ('warning', code, 40):
        print("A warning has been received.")
    case ('error', code, _):
        print(f"An error {code} occurred.")

在上述情况下,test_variable将匹配 (‘error’, code, 100) 和 (‘error’, code, 800)。

  • 守卫
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.")

结构模式匹配的使用跟Java的switch...case语法有点类似!

|操作符

在之前我们需要对一个参数对多类型的匹配时,我们需要使用到Union如下:

from typing import Union

def square(number: Union[int, float]):
    return number ** 2

表示,可以接收int或者float类型的参数,在Python3.10中,我们可以使用|操作符号来简化该操作,如下:

def square(number: int|float):
    return number ** 2

这个新语法也可以作为instance()issublcass()的第二个参数:

>>> isinstance(1, int | str)
True

更多语法变更:https://docs.python.org/3/whatsnew/3.10.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值