Python 3.12 引入了一些新的特性和改進(jìn),提升了開(kāi)發(fā)體驗(yàn)和代碼性能。以下是其中一些值得注意的新函數(shù)和改進(jìn):
雖然這些函數(shù)在 Python 3.9 就已引入,但它們?cè)?Python 3.12 中變得更加廣泛使用。
s = "HelloWorld"print(s.removeprefix("Hello")) # 輸出: Worldprint(s.removesuffix("World")) # 輸出: Hello
返回從 x 開(kāi)始,到 y 方向的下一個(gè)浮點(diǎn)數(shù)。這個(gè)函數(shù)對(duì)需要精確控制浮點(diǎn)數(shù)計(jì)算的場(chǎng)景非常有用。
import mathprint(math.nextafter(1.0, 2.0)) # 輸出: 1.0000000000000002print(math.nextafter(1.0, 0.0)) # 輸出: 0.9999999999999999
這個(gè)屬性允許你訪問(wèn)原始的命令行參數(shù)列表,包括解釋器自身的參數(shù),而不僅僅是腳本和傳遞給腳本的參數(shù)。
import sysprint(sys.orig_argv)
在 Python 3.12 中,functools.cache_clear() 方法被添加到 functools.lru_cache 修飾器中,用于清除緩存。
from functools import lru_cache@lru_cache(maxsize=32)def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)# 清除緩存fibonacci.cache_clear()
Python 3.12 對(duì) typing 模塊進(jìn)行了多項(xiàng)改進(jìn),包括更好的類(lèi)型推斷和新的類(lèi)型提示功能。例如,可以使用 Self 類(lèi)型提示方法的返回類(lèi)型為類(lèi)實(shí)例本身。
from typing import Selfclass MyClass: def my_method(self) -> Self: return self
類(lèi)似于 contextlib.closing 但用于異步生成器對(duì)象。
import contextlibclass AsyncGenerator: async def __aenter__(self): print("Entering") return self async def __aexit__(self, exc_type, exc, tb): print("Exiting") async def __aiter__(self): for i in range(5): yield iasync def main(): async with contextlib.aclosing(AsyncGenerator()) as agen: async for item in agen: print(item)# 運(yùn)行異步主函數(shù)import asyncioasyncio.run(main())
產(chǎn)生一對(duì)連續(xù)元素的迭代器。
import itertoolsfor pair in itertools.pairwise([1, 2, 3, 4]): print(pair)# 輸出: (1, 2), (2, 3), (3, 4)
對(duì)時(shí)區(qū)信息進(jìn)行了增強(qiáng),更好地支持時(shí)間相關(guān)操作。
from zoneinfo import ZoneInfofrom datetime import datetimedt = datetime(2024, 6, 14, tzinfo=ZoneInfo("America/New_York"))print(dt)
這些新特性和改進(jìn)使得 Python 3.12 更加強(qiáng)大和易用,為開(kāi)發(fā)者提供了更多工具來(lái)編寫(xiě)高效、可維護(hù)的代碼。建議大家盡早升級(jí)并嘗試這些新特性。
本文鏈接:http://www.tebozhan.com/showinfo-26-94851-0.html趕緊試試 Python 3.12 吧,真的好用
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com
上一篇: 消滅代碼中的 if :請(qǐng)求參數(shù)校驗(yàn)的優(yōu)雅之道
下一篇: 十分鐘了解 Golang 泛型