最近計(jì)劃將python2遷移到python3,由于本人學(xué)習(xí)時(shí)用的3.7版本,所以僅作大于3.7版本的比較。
3.8
文檔地址:python3.8
新增賦值表達(dá)式:=(海象運(yùn)算符)
作用:避免重復(fù)調(diào)用,使代碼更加簡潔。PS:別當(dāng)GO寫,它不支持聲明并賦值變量
import re
# 3.8
if match := re.search(r"python", "I love python! \r\n And python love me! \r\n", re.I | re.M | re.DOTALL):
print(match.group())
# 3.7
match = re.search(r"python", "I love python! \r\n And python love me! \r\n", re.I | re.M | re.DOTALL)
if match:
print(match.group())
僅限位置形參
作用:
- 新增了一個(gè)函數(shù)形參語法 / 用來指明某些函數(shù)形參必須使用僅限位置而非關(guān)鍵字參數(shù)的形式。
-
/
區(qū)分了前后用什么傳參方式
# *號代表e,f必須用鍵值
# /號代表a,b必須用位置
def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
# 合法調(diào)用
f(10, 20, 30, d=40, e=50, f=60)
# 不合法調(diào)用
f(10, b=20, c=30, d=40, e=50, f=60) # b不能是關(guān)鍵詞參數(shù)
f(10, 20, 30, 40, 50, f=60) # e必須是關(guān)鍵字參數(shù)
3.7的老人感覺:這兩個(gè)符號加上會(huì)降低代碼可讀性
f-字符串支持 = 用于自動(dòng)記錄表達(dá)式和調(diào)試文檔
作用:f’{expr=}’ 的 f-字符串將擴(kuò)展表示為表達(dá)式文本
author = "Generalzy"
print(f'{author=}')
# author='Generalzy'
dict 和 dictview 可以使用 reversed() 按插入順序反向迭代
作用:python3.7開始后,python的dict就有序了,現(xiàn)在支持反轉(zhuǎn)字典順序
dic = {"name": "generalzy", "gender": 1, "age": "2000"}
for key, val in dic.items():
print(key, val)
# name generalzy
# gender 1
# age 2000
print(reversed(dic))
# <dict_reversekeyiterator object at 0x00000257213E71D0>
for key in reversed(dic):
print(key)
# age
# gender
# name
asyncio.run()更加穩(wěn)定
作用:asyncio.run() 已經(jīng)從暫定狀態(tài)晉級為穩(wěn)定 API。 此函數(shù)可被用于執(zhí)行一個(gè) coroutine 并返回結(jié)果,同時(shí)自動(dòng)管理事件循環(huán)
import asyncio
async def main():
await asyncio.sleep(0)
return 42
asyncio.run(main())
因此 asyncio.run() 應(yīng)該作為運(yùn)行 asyncio 程序的首選方式。
csv.DictReader返回值改變
作用:csv.DictReader 現(xiàn)在將返回 dict 而不是 collections.OrderedDict,此工具現(xiàn)在會(huì)更快速且消耗更少內(nèi)存同時(shí)仍然保留字段順序。
multiprocessing增加進(jìn)程間共享內(nèi)存的方法
作用:添加了新的 multiprocessing.shared_memory 模塊。
…
3.9
文檔:python3.9
字典合并 (|)與更新運(yùn)算符(|=)
作用:它們?yōu)楝F(xiàn)有的 dict.update 和 {**d1, **d2} 字典合并方法提供了補(bǔ)充。
>>> x = {"key1": "value1 from x", "key2": "value2 from x"}
>>> y = {"key2": "value2 from y", "key3": "value3 from y"}
>>> x | y
{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}
>>> y | x
{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}
增加了 str.removeprefix(prefix) 和 str.removesuffix(suffix) 用于方便地從字符串移除不需要的前綴或后綴。
作用:用于方便地從字符串移除不需要的前綴或后綴。
標(biāo)準(zhǔn)多項(xiàng)集中的類型標(biāo)注泛型
作用:
- 可以使用內(nèi)置多項(xiàng)集類型例如 list 和 dict 作為通用類型而不必從 typing 導(dǎo)入對應(yīng)的大寫形式類型名 (例如 List 和 Dict)。
- 標(biāo)注類型更加方便了。
def greet_all(names: list[str]) -> None:
for name in names:
print("Hello", name)
新的解析器
Python 3.9 使用于基于 PEG 的新解析器替代 LL(1)。 新解析器的性能與舊解析器大致相當(dāng),但 PEG 在設(shè)計(jì)新語言特性時(shí)的形式化比 LL(1) 更靈活。
file 屬性將是一個(gè)絕對路徑,而不是相對路徑。
作用:__file__在任何情況下都將是一個(gè)絕對路徑
新增時(shí)區(qū)zoneinfo模塊
zoneinfo 模塊為標(biāo)準(zhǔn)庫引入了 IANA 時(shí)區(qū)數(shù)據(jù)庫。 它添加了 zoneinfo.ZoneInfo,這是一個(gè)基于系統(tǒng)時(shí)區(qū)數(shù)據(jù)的實(shí)體 datetime.tzinfo 實(shí)現(xiàn)。
>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime, timedelta
>>> # Daylight saving time
>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-10-31 12:00:00-07:00
>>> dt.tzname()
'PDT'
>>> # Standard time
>>> dt += timedelta(days=7)
>>> print(dt)
2020-11-07 12:00:00-08:00
>>> print(dt.tzname())
PST
random新增方法生成隨機(jī)字節(jié)串
增加了新的 random.Random.randbytes 方法:生成隨機(jī)字節(jié)串。
…
3.10
文檔:python3.10
帶圓括號的上下文管理器
作用:允許將過長的上下文管理器集能夠以與之前 import 語句類似的方式格式化為多行的形式。
with (
CtxManager1() as example1,
CtxManager2() as example2,
CtxManager3() as example3,
):
...
更清楚的錯(cuò)誤消息
結(jié)構(gòu)化模式匹配match…case…語句
作用:類似其他語言的:switch…case…
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case 419 | 420 | 421:
return "我加的"
case _:
return "Something's wrong with the internet"
# 模式和類
class Point:
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):
print(f"Y={y} and the point is on the y-axis.")
case Point(x=x, y=0):
print(f"X={x} and the point is on the x-axis.")
case Point():
print("The point is located somewhere else on the plane.")
case _:
print("Not a point")
# 嵌套模式:模式可以任意地嵌套。
match points:
case []:
print("No points in the list.")
case [Point(0, 0)]:
print("The origin is the only point in the list.")
case [Point(x, y)]:
print(f"A single point {x}, {y} is in the list.")
case [Point(0, y1), Point(0, y2)]:
print(f"Two points on the Y axis at {y1}, {y2} are in the list.")
case _:
print("Something else is found in the list.")
# 約束項(xiàng):可以向一個(gè)模式添加 if 子句,稱為“約束項(xiàng)”。 如果約束項(xiàng)為假值,則 match 將繼續(xù)嘗試下一個(gè) case 語句塊。
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.")
類比一下GO的:
type P struct {
x,y int
}
func main() {
// invalid case []int{...} in switch (can only compare slice a to nil)
//a:=[]int{1,2}
//switch nil{
//case []int{1,2}:
// fmt.Println(a)
//}
p:=P{1,2}
switch p {
case P{1,2}:
fmt.Println(p)
// {1 2}
}
}
新的類型聯(lián)合運(yùn)算符X | Y
作用:簡潔標(biāo)注
def square(number: int | float) -> int | float:
return number ** 2
int 類型新增了一個(gè)方法 int.bit_count()
作用:返回給定整數(shù)的二進(jìn)制展開中值為一的位數(shù),或稱“比特計(jì)量”。
現(xiàn)在 dict.keys(), dict.values() 和 dict.items() 所返回的視圖都有一個(gè) mapping 屬性
作用:給出包裝了原始字典的 types.MappingProxyType 對象。
zip() 函數(shù)有一個(gè)可選的 strict 旗標(biāo)
作用:要求所有可迭代對象的長度都相等,否則異常
…
3.11
文檔:python3.11文章來源:http://www.zghlxwxcb.cn/news/detail-447683.html
比上一個(gè)版本快60%
Self type
作用:標(biāo)注增加self類型文章來源地址http://www.zghlxwxcb.cn/news/detail-447683.html
class MyLock:
def __enter__(self) -> Self:
self.lock()
return self
class MyLock:
def __enter__(self) -> Self:
self.lock()
return self
...
class MyInt:
@classmethod
def fromhex(cls, s: str) -> Self:
return cls(int(s, 16))
...
編譯器現(xiàn)在將優(yōu)化只包含格式代碼 %s, %r 和 %a 的字符串字面值中的簡單 printf 風(fēng)格 % 格式化 并使其速度與對應(yīng)的 f-string 表達(dá)式一樣快。
到了這里,關(guān)于python3.8,3.9,3.10,3.11特性比較的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!