本文實例講述了Python單體模式的幾種常見實現方法。分享給大家供大家參考,具體如下:
這里python實現的單體模式,參考了:https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852#1363852
一、修改父類的 __dict__
class Borg: _shared_state = {} def __init__(self): self.__dict__ = self._shared_stateclass Singleton(Borg): def __init__(self, name): super().__init__() self.name = name def __str__(self): return self.namex = Singleton('sausage')print(x)y = Singleton('eggs')print(y)z = Singleton('spam')print(z)print(x)print(y)注意,這種方法實現的并非真正的單體模式!!
下面幾種方法實現的才是真正的單體模式
二、使用元類
先看看這里關于元類的描述:
元類一般用于創建類。
在執行類定義時,解釋器必須要知道這個類的正確的元類。解釋器會先尋找類屬性__metaclass__,如果此屬性存在,就將這個屬性賦值給此類作為它的元類。如果此屬性沒有定義,它會向上查找父類中的__metaclass__。如果還沒有發現__metaclass__屬性,解釋器會檢查名字為__metaclass__的全局變量,如果它存在,就使用它作為元類。否則, 使用內置的 type 作為此類的元類。
1. 繼承 type,使用 __call__
注意__call__的參數
class Singleton(type): _instance = None def __call__(self, *args, **kw): if self._instance is None: self._instance = super().__call__(*args, **kw) return self._instanceclass MyClass(object): __metaclass__ = Singletonprint(MyClass())print(MyClass())
2. 繼承 type,使用 __new__
注意__new__的參數
class Singleton(type): _instance = None def __new__(cls, name, bases, dct): if cls._instance is None: cls._instance = super().__new__(cls, name, bases, dct) return cls._instanceclass MyClass(object): __metaclass__ = Singletonprint(MyClass())print(MyClass())
3. 繼承 object,使用 __new__
注意__new__的參數
class Singleton(object): _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instanceclass MyClass(object): __metaclass__ = Singletonprint(MyClass())print(MyClass())
下面還有一個很巧妙的方法實現單體模式
使用類方法classmethod
class Singleton: _instance = None @classmethod def create(cls): if cls._instance is None: cls._instance = cls() return cls._instance def __init__(self): self.x = 5 # or whatever you want to dosing = Singleton.create()print(sing.x) # 5sec = Singleton.create()print(sec.x) # 5
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答