<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          重磅來襲!Python3.10正式版發(fā)布了! 我還在用3.6。。。

          共 5751字,需瀏覽 12分鐘

           ·

          2021-10-14 16:22

          來源:juejin.cn/post/7015590447745613854

          Python 3.10正式發(fā)布,你嘗鮮了嗎?

          本文參考自 Python官方文檔 :Python Release Python 3.10.0 | Python.org[1]

          在正值國慶假期人山人海的2021年10月4號,Python官方正式發(fā)布了Python3.10.0[2]。作為一只假期期間宅著不動的coding人,自然是第一時間體驗了一波。相較于之前的版本,該版本有以下主要變更。

          新的 Union Type表達(dá)

          新版本簡化了 Union Type 的使用 ,改為更為簡潔的|

          舊版:

          from?typing?import?Union
          a:?Union[int,?str]?=?1

          新的版本:

          a:?str?|?int?=?1

          二者完全等價:

          Union[int,?str]?==?int?|?str?#?True

          這類變化在其他地方也相似:

          #?舊版:
          #?def?f(list:?List[Union[int,?str]],?param:?Optional[int])?->?Union[float,?str]
          def?f(list:?List[int?|?str],?param:?int?|?None)?->?float?|?str:
          ????pass

          f([1,?"abc"],?None)

          #?舊版:?
          #?typing.List[typing.Union[str,?int]]
          typing.List[str?|?int]
          list[str?|?int]

          #?舊版:?
          #?typing.Dict[str,?typing.Union[int,?float]]
          typing.Dict[str,?int?|?float]
          dict[str,?int?|?float]

          該特性也可用于 isinstanceissubclass

          #?True
          isinstance("FunnySaltyFish",?int|str)

          #?True?
          issubclass(str,?str|int)

          zip 可選嚴(yán)格模式

          zip新增可選參數(shù)strict, 當(dāng)該選項為True時,傳入zip的兩個可迭代項長度必須相等,否則將拋出 ValueError

          舊版(及不加此參數(shù)),當(dāng)二者長度不等時,以長度較小的為準(zhǔn)

          names?=?["a","b","c","d"]
          numbers?=?[1,2,3]
          z?=?zip(names,numbers)
          for?each?in?z:
          ????print(each)
          ????
          #?('a',?1)
          #?('b',?2)
          #?('c',?3)

          設(shè)置strict為True

          #?...
          z?=?zip(names,numbers,strict=True)
          #?...

          d:\projects\python\learn\Py310探索.py?in?
          ??????3?numbers?=?[1,2,3]
          ??????4?z?=?zip(names,numbers,strict=True)
          ---->?5?for?each?in?z:
          ??????6?????print(each)

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

          帶括號的上下文管理器

          with可以加括號了

          with?(CtxManager()?as?example):
          ????...

          with?(
          ????CtxManager1(),
          ????CtxManager2()
          ):
          ????...

          with?(CtxManager1()?as?example,
          ??????CtxManager2()):
          ????...

          with?(CtxManager1(),
          ??????CtxManager2()?as?example):
          ????...

          with?(
          ????CtxManager1()?as?example1,
          ????CtxManager2()?as?example2
          ):
          ????...

          import?pathlib
          p?=?pathlib.Path()
          p1?=?p/"text1.txt"?#?內(nèi)容:文本1的內(nèi)容
          p2?=?p/"text2.txt"?#?內(nèi)容:文本2的內(nèi)容
          with(
          ????p1.open(encoding="utf-8")?as?f1,
          ????p2.open(encoding="utf-8")?as?f2
          ):
          ????print(f1.read(),?f2.read(),?sep="\n")?
          ????
          ????#?文本1的內(nèi)容
          ?#?文本2的內(nèi)容

          顯式類型別名

          使用 TypeAlias 顯式標(biāo)注類型別名,提高可讀性

          舊的方式:

          x?=?int
          def?plus_int(a:x,b:x)?->?x:
          ????return?a+b

          可以看到,x很容易被搞混

          新的方式:使用 TypeAlias表明這是個別名

          from?typing?import?TypeAlias
          x?:?TypeAlias?=?int
          def?plus_int(a:x,b:x)?->?x:
          ????return?a+b

          match...case語句

          對,就是其他語言的switch-case,python終于提供了支持,還是加強(qiáng)版的

          完整語法參見:PEP 634 -- Structural Pattern Matching: Specification | Python.org[3]

          舉幾個例子:

          基本的類型匹配:

          day?=?6
          match?day:
          ????case?1:
          ????????print("星期一")
          ????case?6?|?7:
          ????????print("周末")
          ????case?_?:?
          ????????print("其他情況")

          subject:這在處理命令行參數(shù)的時候特別有用

          """
          ????@copyright?:?[FunnySaltyFish](https://funnysaltyfish.github.io)
          ????@date?:?2021/10/05?21:08:42
          """

          command?=?"save?1.txt"
          #?試著把command改成?list?/?copy?1.txt?2.txt?看看效果
          match?command.split("?"):
          ????case?["list"]:
          ????????print("列出文件~")
          ????case?["save",?file_name]:
          ????????print(f"保存文件到?{file_name}")
          ????case?["copy",source,target]:
          ????????print(f"拷貝?{source}?->?{target}")

          也可以匹配對象:

          class?Person():
          ????pass

          class?Student(Person):
          ????def?__init__(self,?id:?int)?->?None:
          ????????self.id?=?id

          class?Teacher(Person):
          ????def?__init__(self,?name:?str)?->?None:
          ????????self.name?=?name

          a?=?Student(1)
          #?a?=?Student(2)
          #?a?=?Teacher("FunnySaltyFish")
          match?a:
          ????case?Student(id?=?2):
          ????????print(f"這是位學(xué)生,且id正好是2")
          ????case?Student():
          ????????print(f"這是學(xué)生,id為{a.id}")
          ????case?Teacher():
          ????????print(f"這是老師,?姓名為{a.name}")

          當(dāng)然也可以匹配字典:

          d?=?{
          ????"name"?:?"李四",?#?張三
          ????"age"?:?18,
          ????"hobby"?:?"閱讀"
          }?
          match?d:
          ????case?{"name":"張三",?**args}:
          ????????#?**收集其他參數(shù)
          ????????print("這是張三",?args)?#?這是張三?{'age':?18,?'hobby':?'閱讀'}
          ????case?{"name"?:?name?,?"age"?:?age,?"hobby":?hobby}:
          ????????print(f"我叫{name},?今年{age}歲,?喜歡{hobby}")?#我叫李四,今年18歲,喜歡閱讀

          更復(fù)雜的還有結(jié)合Guard、匹配捕獲等使用,具體可以參見:PEP 635 -- Structural Pattern Matching: Motivation and Rationale | Python.org[4]PEP 636 -- Structural Pattern Matching: Tutorial | Python.org[5]

          更友好的報錯提示

          現(xiàn)在,當(dāng)你的括號、引號未閉合時,python會拋出更加清晰明了的錯誤

          str?=?"未閉合的str

          File?"
          d:\projects\python\learn\Py310探索.py",?line?90
          ????str?=?"
          未閉合的str
          ??????????^
          SyntaxError:?unterminated?string?literal?(detected?at?line?90)

          ?arr?=?[1,?2,?2,?3
          ????
          ??File?"d:\projects\python\learn\Py310探索.py",?line?91
          ????arr?=?[1,?2,?2,?3
          ??????????^
          SyntaxError:?'['?was?never?closed

          其他一些更新:

          distutils 被棄用

          推薦使用 setuptools

          需要 OpenSSL 1.1.1 及以上版本
          移除 Py_UNICODE編碼API
          PyUnicodeObject的wstr被棄用,并將在之后移除

          完。摸魚去了。

          參考資料

          [1]

          https://www.python.org/downloads/release/python-3100/: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdownloads%2Frelease%2Fpython-3100%2F

          [2]

          https://www.python.org/downloads/release/python-3100/: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdownloads%2Frelease%2Fpython-3100%2F

          [3]

          https://www.python.org/dev/peps/pep-0634/#id25: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdev%2Fpeps%2Fpep-0634%2F%23id25

          [4]

          https://www.python.org/dev/peps/pep-0635/#id15: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdev%2Fpeps%2Fpep-0635%2F%23id15

          [5]

          https://www.python.org/dev/peps/pep-0636/: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdev%2Fpeps%2Fpep-0636%2F





          推薦閱讀:

          入門:?最全的零基礎(chǔ)學(xué)Python的問題? |?零基礎(chǔ)學(xué)了8個月的Python??|?實戰(zhàn)項目?|學(xué)Python就是這條捷徑


          量化:?定投基金到底能賺多少錢?? |?我用Python對去年800只基金的數(shù)據(jù)分析??


          干貨:爬取豆瓣短評,電影《后來的我們》?|?38年NBA最佳球員分析?|? ?從萬眾期待到口碑撲街!唐探3令人失望? |?笑看新倚天屠龍記?|?燈謎答題王?|用Python做個海量小姐姐素描圖?|碟中諜這么火,我用機(jī)器學(xué)習(xí)做個迷你推薦系統(tǒng)電影


          趣味:彈球游戲? |?九宮格? |?漂亮的花?|?兩百行Python《天天酷跑》游戲!


          AI:?會做詩的機(jī)器人?|?給圖片上色?|?預(yù)測收入?|?碟中諜這么火,我用機(jī)器學(xué)習(xí)做個迷你推薦系統(tǒng)電影


          小工具:?Pdf轉(zhuǎn)Word,輕松搞定表格和水印!?|?一鍵把html網(wǎng)頁保存為pdf!|??再見PDF提取收費!?|?用90行代碼打造最強(qiáng)PDF轉(zhuǎn)換器,word、PPT、excel、markdown、html一鍵轉(zhuǎn)換?|?制作一款釘釘?shù)蛢r機(jī)票提示器!?|60行代碼做了一個語音壁紙切換器天天看小姐姐!


          年度爆款文案


          點閱讀原文,更多好玩Python!

          瀏覽 40
          點贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产性爱无码视频 | 国产又黄又| 十八禁免费观看网站 | 日日夜夜天天 | 婷婷激情在线视频 |