萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 元類實現 Singleton 模式:__call__ 控制實例化

Singleton 確保類全程序僅有一個實例。Python 透過元類(metaclass)攔截 __call__(即 Class() 呼叫)實現最純粹的單例,無需修改業務類、無需基類繼承、執行緒安全(需額外鎖)。

元類實現


class Singleton(type):
    def __call__(cls, *args, **kwargs):
        print("Singleton call")
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls.instance

    def __new__(cls, name, bases, dct):
        print("Singleton new")
        return type.__new__(cls, name, bases, dct)

    def __init__(cls, name, bases, dct):
        print("Singleton init")
        super(Singleton, cls).__init__(name, bases, dct)

class Cache(object):
    __metaclass__ = Singleton  # Python 2 語法;Py3 用 class Cache(metaclass=Singleton):

    def __new__(cls, *args, **kwargs):
        print("Cache new")
        return object.__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        print("Cache init")

    def __call__(self, *args, **kwargs):
        print("Cache call")

執行流程與輸出


print(Cache())
print(Cache())

# 輸出:
Singleton new
Singleton init
Singleton call
Cache new
Cache init
<__main__.Cache object at 0x...>
Singleton call
<__main__.Cache object at 0x...>  # 同一物件

關鍵點

  1. __new__:建立類物件(元類層面),僅在類定義時執行一次。
  2. __init__:初始化類物件,亦僅一次。
  3. __call__:每次 Cache() 呼叫都會觸發,攔截實例化邏輯。
  4. 業務類 Cache 完全不知情,符合開閉原則。

Python 3 語法


class Cache(metaclass=Singleton):
    ...

執行緒安全版(雙重檢查鎖)


import threading

class Singleton(type):
    _instances = {}
    _lock = threading.Lock()

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            with cls._lock:
                if cls not in cls._instances:
                    cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

其他單例寫法對比

元類單例是框架級基礎設施(如 ORM 連線池、配置管理、日誌器)的首選模式,掌握其 __new__/__init__/__call__ 三階段生命週期,能駕馭更多進階元編程場景。

copyright © 萬盛學電腦網 all rights reserved
方法優點缺點
模組級變數最簡單、Pythonic非類介面、難以延遲初始化
裝飾器非侵入、可參數化返回函式非類、isinstance 失效
基類 __new__繼承即得需繼承、多重繼承易衝突
元類 __call__透明、支援繼承、可攔截建構參數稍難理解、元類衝突需注意