亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

一、核心意義與機(jī)制

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

1.2 與 __init__ 對(duì)比

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

二、核心功能解析

2.1 核心能力

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

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要?jiǎng)?chuàng)建的類名(如 "MyClass")
basestuple基類列表(繼承的父類)
attrsdict類屬性字典(包含方法、類變量等)

調(diào)用邏輯

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

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

樣例

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

調(diào)用邏輯

  • 繼承自不可變類型(str/int/tuple 等)
  • 必須通過 __new__ 完成實(shí)例創(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`當(dāng)前類對(duì)象(Singleton)
*argstuple位置參數(shù)(與 __init__ 共享參數(shù))
?**?kwargsdict關(guān)鍵字參數(shù)(與 __init__ 共享參數(shù))

調(diào)用邏輯

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

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

2.4 核心記憶要點(diǎn)

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

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

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

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

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

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

三、典型應(yīng)用場(chǎng)景

3.1 單例模式實(shí)現(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 不可變類型擴(kuò)展

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

3.3 對(duì)象池技術(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()

四、高級(jí)應(yīng)用技巧

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ù)預(yù)處理

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__"

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

6.1 常見錯(cuò)誤

class ErrorCase:
    def __new__(cls):
        # 錯(cuò)誤:忘記返回實(shí)例
        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 對(duì)象緩存策略

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):
        # 避免重復(fù)初始化
        self.config = config

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

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

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

相關(guān)文章

  • python二維列表一維列表的互相轉(zhuǎn)換實(shí)例

    python二維列表一維列表的互相轉(zhuǎn)換實(shí)例

    今天小編就為大家分享一篇python二維列表一維列表的互相轉(zhuǎn)換實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • 詳解Python數(shù)據(jù)分析--Pandas知識(shí)點(diǎn)

    詳解Python數(shù)據(jù)分析--Pandas知識(shí)點(diǎn)

    這篇文章主要介紹了Python數(shù)據(jù)分析--Pandas知識(shí)點(diǎn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • Python爬蟲爬取美劇網(wǎng)站的實(shí)現(xiàn)代碼

    Python爬蟲爬取美劇網(wǎng)站的實(shí)現(xiàn)代碼

    一直在學(xué)習(xí)Python爬蟲,所以今天就心血來潮來寫了個(gè)爬蟲,抓取該網(wǎng)站上所有美劇鏈接,并保存在文本文檔中,想要哪部劇就直接打開復(fù)制鏈接到迅雷就可以下載啦
    2016-09-09
  • Python序列對(duì)象與String類型內(nèi)置方法詳解

    Python序列對(duì)象與String類型內(nèi)置方法詳解

    這篇文章主要介紹了Python序列對(duì)象與String類型內(nèi)置方法,結(jié)合實(shí)例形式分析了Python序列對(duì)象與String類型各種常見內(nèi)置方法相關(guān)使用技巧及操作注意事項(xiàng),需要的朋友可以參考下
    2019-10-10
  • PyQt5每天必學(xué)之事件與信號(hào)

    PyQt5每天必學(xué)之事件與信號(hào)

    這篇文章主要為大家詳細(xì)介紹了PyQt5每天必學(xué)之事件與信號(hào)的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • pyTorch深度學(xué)習(xí)softmax實(shí)現(xiàn)解析

    pyTorch深度學(xué)習(xí)softmax實(shí)現(xiàn)解析

    這篇文章主要介紹了pytorch深度學(xué)習(xí)中對(duì)softmax實(shí)現(xiàn)進(jìn)行了詳細(xì)解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2021-09-09
  • Python中常見的導(dǎo)入方式總結(jié)

    Python中常見的導(dǎo)入方式總結(jié)

    這篇文章主要介紹了Python中常見的導(dǎo)入方式總結(jié),文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-05-05
  • Django app配置多個(gè)數(shù)據(jù)庫(kù)代碼實(shí)例

    Django app配置多個(gè)數(shù)據(jù)庫(kù)代碼實(shí)例

    這篇文章主要介紹了Django app配置多個(gè)數(shù)據(jù)庫(kù)代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • 詳解Python 3D引擎Ursina如何繪制立體圖形

    詳解Python 3D引擎Ursina如何繪制立體圖形

    Python有一個(gè)不錯(cuò)的3D引擎——Ursina。本文就來手把手教你認(rèn)識(shí)Ursina并學(xué)會(huì)繪制立體圖形,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-01-01
  • Sanic框架路由用法實(shí)例分析

    Sanic框架路由用法實(shí)例分析

    這篇文章主要介紹了Sanic框架路由用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Sanic框架路由的原理、請(qǐng)求參數(shù)、請(qǐng)求類型、重定向等相關(guān)操作技巧,需要的朋友可以參考下
    2018-07-07

最新評(píng)論