熱線電話:13121318867

登錄
首頁精彩閱讀python 3.10 的新特性用不到,你來打我
python 3.10 的新特性用不到,你來打我
2021-10-15
收藏
<a href='/map/python/' style='color:#000;font-size:inherit;'>python</a> 3.10 的新特性用不到,你來打我

作者:某某白米飯

來源:Python 技術

python 3.10 已經在 10月 4 號發布了,這次更新了錯誤語法提示對 python 新手更加友好。好幾個新的特性非常的有用,一起來看看吧。

更細致的錯誤語法提示

在調試代碼的時候可以精確定位到錯誤語法的那行,而不是提示 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'? 

結構化模式匹配:match...case

相當于其他語言的 switch...case

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

關鍵字 match 后跟變量名。 如果匹配,則將執行 case 塊內的語句, 沒有匹配,則執行 case _ 塊內的語句。

# 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('放假了')

結果:

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

再來一個 tuple 類型的

# 2 point = (1, 2, 3)
match point:
    case (0, 0, _):
        print("原點")
    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")

結果:

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

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

新型聯合運算符

以 X|Y 的形式引入了新的類型聯合運算符。

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

結果:

16 19.360000000000003 

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

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

結果:

True True 

zip 的嚴格模式

函數 zip() 增加 strict 參數,如果設置 strict = True,而傳輸的參數的長度不相等將會拋出異常。

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

結果:

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)

總結

python 3.10 更新的最有用的就是錯誤提示了,再也不會看到提示一團迷糊,定位更加的精確,match...case 終于來了。

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢