最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中的魔術(shù)方法__new__詳解

 更新時間:2025年04月14日 15:33:25   作者:Yant224  
這篇文章主要介紹了Python中的魔術(shù)方法__new__的使用,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

一、核心意義與機制

1.1 構(gòu)造過程原理

1.2 與 __init__ 對比

特性__new____init__
方法類型靜態(tài)方法實例方法
返回值必須返回實例對象無返回值
調(diào)用時機創(chuàng)建實例時首先調(diào)用在 __new__ 之后調(diào)用
主要職責控制實例創(chuàng)建過程初始化實例屬性

二、核心功能解析

2.1 核心能力

  • 控制實例創(chuàng)建過程
  • 決定是否生成新實例
  • 修改實例創(chuàng)建邏輯
  • 實現(xiàn)設計模式底層支持

2.2 方法簽名

元類中的 __new__ 參數(shù)(示例 4.1)

  • 樣例
class Meta(type):
    def __new__(mcs, name, bases, attrs):
        # 參數(shù)列表固定
        return super().__new__(mcs, name, bases, attrs)
  • 參數(shù)解析表
參數(shù)名類型說明
mcstype元類自身(約定命名,類似 cls 代表類)
namestr要創(chuàng)建的類名(如 "MyClass")
basestuple基類列表(繼承的父類)
attrsdict類屬性字典(包含方法、類變量等)

調(diào)用邏輯

  • 元類用于??創(chuàng)建類對象??(不是實例對象)
  • 參數(shù)由解釋器在定義類時自動傳入
  • super().__new__ 最終調(diào)用 type.__new__ 生成類對象

不可變類型子類的 __new__(示例 3.2)

樣例

class ImmutableStr(str):
    def __new__(cls, value):
        return super().__new__(cls, processed_value)
  • 參數(shù)解析表
參數(shù)名類型說明
clstype當前類對象(ImmutableStr)
valueAny用戶自定義參數(shù)(初始化輸入值)

調(diào)用邏輯

  • 繼承自不可變類型(str/int/tuple 等)
  • 必須通過 __new__ 完成實例創(chuàng)建
  • super().__new__ 調(diào)用父類(str)的構(gòu)造方法
  • 參數(shù)需匹配父類 __new__ 的要求(如 str 需要傳入初始化字符串)

可變類型普通類的 __new__(示例 3.1)

樣例

class Singleton:
    def __new__(cls, *args, ?**?kwargs):
        return super().__new__(cls)
  • 參數(shù)解析表
參數(shù)名類型說明
cls`當前類對象(Singleton)
*argstuple位置參數(shù)(與 __init__ 共享參數(shù))
?**?kwargsdict關(guān)鍵字參數(shù)(與 __init__ 共享參數(shù))

調(diào)用邏輯

  • 普通類的實例創(chuàng)建流程
  • super().__new__ 調(diào)用 object.__new__ 生成實例
  • 參數(shù)需與 __init__ 方法兼容

2.3 參數(shù)傳遞關(guān)系圖示

2.4 核心記憶要點

??元類 __new__ 的四個參數(shù)是固定結(jié)構(gòu)??

  • 用于構(gòu)建類對象(類的模板)
  • 參數(shù)由解釋器自動填充

??普通類 __new__ 第一個參數(shù)必為 cls??

  • 后續(xù)參數(shù)需與 __init__ 匹配
  • 不可變類型需要完全重寫參數(shù)列表

??super().__new__ 的參數(shù)必須與父類一致??

  • 元類中:super().__new__(mcs, name, bases, attrs)
  • 普通類中:super().__new__(cls[, ...])

三、典型應用場景

3.1 單例模式實現(xiàn)

class Singleton:
    _instance = None
    
    def __new__(cls, *args, ?**?kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

a = Singleton()
b = Singleton()
print(a is b)  # True

3.2 不可變類型擴展

class ImmutableStr(str):
    def __new__(cls, value):
        # 預處理字符串
        processed = value.strip().upper()
        return super().__new__(cls, processed)
    
s = ImmutableStr("  hello  ")
print(s)  # "HELLO"

3.3 對象池技術(shù)

class ConnectionPool:
    _pool = []
    _max_size = 5
    
    def __new__(cls):
        if len(cls._pool) < cls._max_size:
            obj = super().__new__(cls)
            cls._pool.append(obj)
            return obj
        return cls._pool.pop(0)

conn1 = ConnectionPool()
conn2 = ConnectionPool()

四、高級應用技巧

4.1 元類協(xié)作

class Meta(type):
    def __new__(mcs, name, bases, attrs):
        # 添加類屬性
        attrs['version'] = 1.0
        return super().__new__(mcs, name, bases, attrs)

class MyClass(metaclass=Meta):
    pass

print(MyClass.version)  # 1.0

4.2 參數(shù)預處理

class SmartTuple(tuple):
    def __new__(cls, iterable):
        # 過濾非數(shù)字元素
        filtered = (x for x in iterable if isinstance(x, (int, float)))
        return super().__new__(cls, filtered)
    
t = SmartTuple([1, 'a', 3.14, None])
print(t)  # (1, 3.14)

五、繼承體系中的使用

5.1 繼承鏈處理

class Base:
    def __new__(cls, *args, ?**?kwargs):
        print(f"Creating {cls.__name__}")
        return super().__new__(cls)

class Child(Base):
    pass

c = Child()  # 輸出 "Creating Child"

5.2 多繼承處理

class A:
    def __new__(cls, *args, ?**?kwargs):
        print("A's __new__")
        return super().__new__(cls)

class B:
    def __new__(cls, *args, ?**?kwargs):
        print("B's __new__")
        return super().__new__(cls)

class C(A, B):
    def __new__(cls, *args, ?**?kwargs):
        return A.__new__(cls)

obj = C()  # 輸出 "A's __new__"

六、注意事項與調(diào)試

6.1 常見錯誤

class ErrorCase:
    def __new__(cls):
        # 錯誤:忘記返回實例
        print("Creating instance")  # ? 無返回值
        
    def __init__(self):
        print("Initializing")

e = ErrorCase()  # TypeError

6.2 調(diào)試技巧

class DebugClass:
    def __new__(cls, *args, ?**?kwargs):
        print(f"__new__ args: {args}")
        instance = super().__new__(cls)
        print(f"Instance ID: {id(instance)}")
        return instance
    
    def __init__(self, value):
        print(f"__init__ value: {value}")

d = DebugClass(42)

七、性能優(yōu)化建議

7.1 對象緩存策略

class ExpensiveObject:
    _cache = {}
    
    def __new__(cls, config):
        key = hash(frozenset(config.items()))
        if key not in cls._cache:
            instance = super().__new__(cls)
            instance._init(config)
            cls._cache[key] = instance
        return cls._cache[key]
    
    def __init__(self, config):
        # 避免重復初始化
        self.config = config

最佳實踐總結(jié)??

  • 優(yōu)先使用 super().__new__ 保證繼承鏈正常
  • 修改不可變類型必須使用 __new__
  • 單例模式要處理好線程安全問題
  • 避免在 __new__ 中做耗時操作

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python中判斷列表是否包含某個元素的方法大全

    Python中判斷列表是否包含某個元素的方法大全

    在Python編程中,判斷一個列表是否包含特定元素是一項常見任務,本文將深入研究各種方法,從基本的成員運算符到更高級的函數(shù)和庫的應用,需要的朋友可以參考下
    2026-01-01
  • pytorch的梯度計算以及backward方法詳解

    pytorch的梯度計算以及backward方法詳解

    今天小編就為大家分享一篇pytorch的梯度計算以及backward方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python基于React-Dropzone實現(xiàn)上傳組件的示例代碼

    Python基于React-Dropzone實現(xiàn)上傳組件的示例代碼

    本文主要介紹了在React-Flask框架上開發(fā)上傳組件的技巧。文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • Python3環(huán)境安裝Scrapy爬蟲框架過程及常見錯誤

    Python3環(huán)境安裝Scrapy爬蟲框架過程及常見錯誤

    這篇文章主要介紹了Python3環(huán)境安裝Scrapy爬蟲框架過程及常見錯誤 ,本文給大家介紹的非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-07-07
  • Python中的哈希算法模塊hashlib詳解

    Python中的哈希算法模塊hashlib詳解

    這篇文章主要介紹了Python中的哈希算法模塊hashlib詳解,hashlib模塊實現(xiàn)了多種哈希算法,包括MD5以及SHA家族的算法,通過algorithms_guaranteed可以查看hashlib中封裝的所有算法,需要的朋友可以參考下
    2023-08-08
  • 詳解python之heapq模塊及排序操作

    詳解python之heapq模塊及排序操作

    說到排序,很多人可能第一想到的就是sorted,但是你可能不知道python中其實還有還就中方法喲,并且好多種場景下效率都會比sorted高。那么接下來我就依次來介紹我所知道的排序操作
    2019-04-04
  • Python+tkinter實現(xiàn)動態(tài)連接數(shù)據(jù)庫

    Python+tkinter實現(xiàn)動態(tài)連接數(shù)據(jù)庫

    在使用 Tkinter (tk) 開發(fā) GUI 程序時,可以通過多種方式讓用戶自由更改數(shù)據(jù)庫連接地址,本文主要介紹了三種常用方法,感興趣的小伙伴可以了解下
    2025-03-03
  • 使用Python實現(xiàn)加密或解密Word文檔

    使用Python實現(xiàn)加密或解密Word文檔

    在日常辦公和文檔管理中,保護敏感信息的安全性至關(guān)重要,本文詳細介紹了使用?Spire.Doc?for?Python?對?Word?文檔進行加密和解密的多種方法,感興趣的小伙伴可以了解下
    2026-05-05
  • python制作圖片縮略圖

    python制作圖片縮略圖

    這篇文章主要為大家詳細介紹了python制作圖片縮略圖的相關(guān)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-04-04
  • Python使用5行代碼批量做小姐姐的素描圖

    Python使用5行代碼批量做小姐姐的素描圖

    本文主要介紹了Python使用5行代碼批量做小姐姐的素描圖,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07

最新評論

建始县| 治多县| 安远县| 胶南市| 邯郸市| 民勤县| 涪陵区| 鞍山市| 上思县| 绥化市| 桂阳县| 虎林市| 资阳市| 道真| 凌海市| 湖北省| 东乡| 双江| 深泽县| 三门县| 龙海市| 景德镇市| 噶尔县| 察隅县| 叶城县| 汉沽区| 皮山县| 三江| 绥化市| 司法| 石屏县| 璧山县| 临清市| 兴宁市| 马山县| 宿松县| 凤山市| 新乐市| 井研县| 开原市| 美姑县|