99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話: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 已經(jīng)在 10月 4 號發(fā)布了,這次更新了錯誤語法提示對 python 新手更加友好。好幾個新的特性非常的有用,一起來看看吧。

更細致的錯誤語法提示

在調(diào)試代碼的時候可以精確定位到錯誤語法的那行,而不是提示 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é)構化模式匹配: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 后跟變量名。 如果匹配,則將執(zhí)行 case 塊內(nèi)的語句, 沒有匹配,則執(zhí)行 case _ 塊內(nèi)的語句。

# 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 周一
周二
周三
周四
周五
放假了
放假了

再來一個 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")

結(jié)果:

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

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

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

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

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

結(jié)果:

16 19.360000000000003 

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

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

結(jié)果:

True True 

zip 的嚴格模式

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

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 更新的最有用的就是錯誤提示了,再也不會看到提示一團迷糊,定位更加的精確,match...case 終于來了。

數(shù)據(jù)分析咨詢請掃描二維碼

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

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }