編程學(xué)習(xí)網(wǎng) > 編程語(yǔ)言 > Python > python 3.10 的新特性用不到,你來(lái)打我!!!
2022
07-16

python 3.10 的新特性用不到,你來(lái)打我!!!

python 3.10 已經(jīng)在 10月 4 號(hào)發(fā)布了,這次更新了錯(cuò)誤語(yǔ)法提示對(duì) python 新手更加友好。好幾個(gè)新的特性非常的有用,一起來(lái)看看吧。

更細(xì)致的錯(cuò)誤語(yǔ)法提示

在調(diào)試代碼的時(shí)候可以精確定位到錯(cuò)誤語(yǔ)法的那行,而不是提示 SyntaxError 的行。

# 1 expected = {9: 1, 18: 2, 19: 2, 27: 3, 
some_other_code = foo() # 2 foo(x, z for z in range(10), t, w) # 3  try:
    build_dyson_sphere() except NotEnoughScienceError, NotEnoughResourcesError: # 4 f"Black holes {*all_black_holes} and revelations" # 5 schwarzschild_black_hole = None schwarschild_black_hole

3.9 提示的是

# 1      some_other_code = foo()
                    ^
SyntaxError: invalid syntax # 2      foo(x, z for z in range(10), t, w)
           ^
SyntaxError: Generator expression must be parenthesized # 3     except NotEnoughScienceError, NotEnoughResourcesError:
                                ^
SyntaxError: invalid syntax # 4     (*all_black_holes)
     ^
SyntaxError: f-string: can't use starred expression here

# 5
    schwarschild_black_hole
NameError: name 'schwarschild_black_hole' is not defined 

3.10 提示的是

# 1     expected = {9: 1, 18: 2, 19: 2, 27: 3, 
               ^
SyntaxError: '{' was never closed # 2     foo(x, z for z in range(10), t, w)
           ^^^^^^^^^^^^^^^^^^^^
SyntaxError: Generator expression must be parenthesized # 3     except NotEnoughScienceError, NotEnoughResourcesError:
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: multiple exception types must be parenthesized # 4     (*all_black_holes)
     ^^^^^^^^^^^^^^^^
SyntaxError: f-string: cannot use starred expression here # 5     schwarschild_black_hole
NameError: name 'schwarschild_black_hole' is not defined. Did you mean: 'schwarzschild_black_hole'?

結(jié)構(gòu)化模式匹配:match...case

相當(dāng)于其他語(yǔ)言的 switch...case

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

關(guān)鍵字 match 后跟變量名。 如果匹配,則將執(zhí)行 case 塊內(nèi)的語(yǔ)句, 沒有匹配,則執(zhí)行 case _ 塊內(nèi)的語(yǔ)句。

# 1 for i in [1,2,3,4,5,6,7]:
    match i:
        case 1:
            print('周一')
        case 2:
            print('周二')
        case 3:
            print('周三')
        case 4:
            print('周四')
        case 5:
            print('周五')
        case _:
            print('放假了')

結(jié)果:

# 1 周一
周二
周三
周四
周五
放假了
放假了

再來(lái)一個(gè) tuple 類型的

# 2 point = (1, 2, 3)
match point:
    case (0, 0, _):
        print("原點(diǎn)")
    case (0, y, 0):
        print(f"Y={y}")
    case (x, 0, 0):
        print(f"X={x}")
    case (x, y, z):
        print(f"X={x}, Y={y}, Z={z}")
    case _:
        raise ValueError("Not a point")

結(jié)果:

# 2 X=1, Y=2, Z=3 

可以使用 tuple 類型,當(dāng)然也可以使用 list 類型,類似于:points = [(1, 3),(1, 2)]

新型聯(lián)合運(yùn)算符

以 X|Y 的形式引入了新的類型聯(lián)合運(yùn)算符。

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

結(jié)果:

16 19.360000000000003 

也可以用作 isinstance():一個(gè)對(duì)象是否是一個(gè)已知的類型 和 issubclass():判斷參數(shù) class 是否是類型參數(shù) classinfo 的子類 的第二個(gè)參數(shù)。

isinstance("5",int|str) 
isinstance("xxxx",int|str) 

結(jié)果:

True True 

zip 的嚴(yán)格模式

函數(shù) zip() 增加 strict 參數(shù),如果設(shè)置 strict = True,而傳輸?shù)膮?shù)的長(zhǎng)度不相等將會(huì)拋出異常。

x = [1,2,3,4,5]
y = [1,2,3]
z = zip(x,y, strict=True)
print(list(z))

結(jié)果:

ValueError: zip() argument 2 is shorter than argument 1 

字典增加了 mapping 屬性

dict.items()、dict.keys()、dict.values() 分別增加了 mapping 屬性

x = {'name': '張三', 'age': 14}
keys = x.keys()
values = x.values()
items = x.items()
print(keys.mapping)
print(values.mapping)
print(items.mapping)

總結(jié)

python 3.10 更新的最有用的就是錯(cuò)誤提示了,再也不會(huì)看到提示一團(tuán)迷糊,定位更加的精確,match...case 終于來(lái)了。想了解更多關(guān)于Python教程或者相關(guān)資訊歡迎持續(xù)關(guān)注編程學(xué)習(xí)網(wǎng)

掃碼二維碼 獲取免費(fèi)視頻學(xué)習(xí)資料

Python編程學(xué)習(xí)

查 看2022高級(jí)編程視頻教程免費(fèi)獲取