自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

趕緊試試 Python 3.12 吧,真的好用

開發(fā) 前端
Python 3.12 引入了一些新的特性和改進,提升了開發(fā)體驗和代碼性能。以下是其中一些值得注意的新函數和改進。

Python 3.12 引入了一些新的特性和改進,提升了開發(fā)體驗和代碼性能。以下是其中一些值得注意的新函數和改進:

1. str.removeprefix() and str.removesuffix()

雖然這些函數在 Python 3.9 就已引入,但它們在 Python 3.12 中變得更加廣泛使用。

  • **str.removeprefix(prefix)**:如果字符串以指定的前綴開頭,則返回去掉該前綴的字符串。
  • **str.removesuffix(suffix)**:如果字符串以指定的后綴結尾,則返回去掉該后綴的字符串。

s = "HelloWorld"
print(s.removeprefix("Hello"))  # 輸出: World
print(s.removesuffix("World"))  # 輸出: Hello

2. math.nextafter(x, y)

返回從 x 開始,到 y 方向的下一個浮點數。這個函數對需要精確控制浮點數計算的場景非常有用。

import math

print(math.nextafter(1.0, 2.0))  # 輸出: 1.0000000000000002
print(math.nextafter(1.0, 0.0))  # 輸出: 0.9999999999999999

3. sys.orig_argv

這個屬性允許你訪問原始的命令行參數列表,包括解釋器自身的參數,而不僅僅是腳本和傳遞給腳本的參數。

import sys

print(sys.orig_argv)

4. functools.cache_clear()

在 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()

5. 新的 typing 模塊改進

Python 3.12 對 typing 模塊進行了多項改進,包括更好的類型推斷和新的類型提示功能。例如,可以使用 Self 類型提示方法的返回類型為類實例本身。

from typing import Self

class MyClass:
    def my_method(self) -> Self:
        return self

6. contextlib.aclosing

類似于 contextlib.closing 但用于異步生成器對象。

import contextlib

class 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 i

async def main():
    async with contextlib.aclosing(AsyncGenerator()) as agen:
        async for item in agen:
            print(item)

# 運行異步主函數
import asyncio
asyncio.run(main())

7. itertools.pairwise()

產生一對連續(xù)元素的迭代器。

import itertools

for pair in itertools.pairwise([1, 2, 3, 4]):
    print(pair)
# 輸出: (1, 2), (2, 3), (3, 4)

8. zoneinfo 模塊改進

對時區(qū)信息進行了增強,更好地支持時間相關操作。

from zoneinfo import ZoneInfo
from datetime import datetime

dt = datetime(2024, 6, 14, tzinfo=ZoneInfo("America/New_York"))
print(dt)

這些新特性和改進使得 Python 3.12 更加強大和易用,為開發(fā)者提供了更多工具來編寫高效、可維護的代碼。建議大家盡早升級并嘗試這些新特性。

責任編輯:趙寧寧 來源: 老貓coder
相關推薦

2024-03-11 08:21:49

2020-04-20 10:10:52

Python數據可視化數據科學

2022-04-28 23:08:40

Windows 10微軟功能

2023-12-18 11:26:57

編程語言Pythonswitch

2012-03-27 09:20:57

Java

2020-11-18 09:37:07

程序員技術996

2022-10-09 10:02:09

Python3.12

2024-10-28 10:55:50

Jedis組件客戶端

2023-02-27 08:53:54

JedislettuceRedis

2022-05-09 08:06:43

Linux命令工具

2020-04-03 14:25:55

diff Meld工具

2014-12-25 15:33:16

2023-12-21 07:13:08

Python工具移除

2021-03-05 22:57:25

遞歸閉包 Python

2022-06-17 11:10:43

PandasPolarsPython

2022-04-24 10:12:25

Python軟件包代碼

2010-01-15 16:45:35

C++語言

2020-12-02 08:31:47

Elasticsear

2020-10-26 08:06:59

網絡技巧CSS

2013-04-18 09:43:34

碼農網站網站設計
點贊
收藏

51CTO技術棧公眾號