Python單體模式的幾種常見實現(xiàn)方法詳解
本文實例講述了Python單體模式的幾種常見實現(xiàn)方法。分享給大家供大家參考,具體如下:
這里python實現(xiàn)的單體模式,參考了:https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852#1363852
一、修改父類的 __dict__
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(Borg):
def __init__(self, name):
super().__init__()
self.name = name
def __str__(self):
return self.name
x = Singleton('sausage')
print(x)
y = Singleton('eggs')
print(y)
z = Singleton('spam')
print(z)
print(x)
print(y)
注意,這種方法實現(xiàn)的并非真正的單體模式??!
下面幾種方法實現(xiàn)的才是真正的單體模式
二、使用元類
先看看這里關(guān)于元類的描述:
元類一般用于創(chuàng)建類。
在執(zhí)行類定義時,解釋器必須要知道這個類的正確的元類。解釋器會先尋找類屬性__metaclass__,如果此屬性存在,就將這個屬性賦值給此類作為它的元類。如果此屬性沒有定義,它會向上查找父類中的__metaclass__。如果還沒有發(fā)現(xiàn)__metaclass__屬性,解釋器會檢查名字為__metaclass__的全局變量,如果它存在,就使用它作為元類。否則, 使用內(nèi)置的 type 作為此類的元類。
1. 繼承 type,使用 __call__
注意__call__的參數(shù)
class Singleton(type):
_instance = None
def __call__(self, *args, **kw):
if self._instance is None:
self._instance = super().__call__(*args, **kw)
return self._instance
class MyClass(object):
__metaclass__ = Singleton
print(MyClass())
print(MyClass())
2. 繼承 type,使用 __new__
注意__new__的參數(shù)
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._instance
class MyClass(object):
__metaclass__ = Singleton
print(MyClass())
print(MyClass())
3. 繼承 object,使用 __new__
注意__new__的參數(shù)
class Singleton(object):
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
class MyClass(object):
__metaclass__ = Singleton
print(MyClass())
print(MyClass())
下面還有一個很巧妙的方法實現(xiàn)單體模式
使用類方法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 do
sing = Singleton.create()
print(sing.x) # 5
sec = Singleton.create()
print(sec.x) # 5
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python+selenium實現(xiàn)自動化百度搜索關(guān)鍵詞
在本篇文章里我們給大家分享了一篇關(guān)于python+selenium實現(xiàn)自動化百度搜索關(guān)鍵詞的實例文章,需要的朋友們可以跟著操作下。2019-06-06
python 簡單照相機調(diào)用系統(tǒng)攝像頭實現(xiàn)方法 pygame
今天小編就為大家分享一篇python 簡單照相機調(diào)用系統(tǒng)攝像頭實現(xiàn)方法 pygame,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
使用Python文件讀寫,自定義分隔符(custom delimiter)
這篇文章主要介紹了使用Python文件讀寫,自定義分隔符(custom delimiter),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07

