簡(jiǎn)單了解python單例模式的幾種寫法
方法一:使用裝飾器
裝飾器維護(hù)一個(gè)字典對(duì)象instances,緩存了所有單例類,只要單例不存在則創(chuàng)建,已經(jīng)存在直接返回該實(shí)例對(duì)象。
def singleton(cls): instances = {} def wrapper(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return wrapper @singleton class Foo(object): pass foo1 = Foo() foo2 = Foo() print foo1 is foo2
方法二:使用基類
__new__是真正創(chuàng)建實(shí)例對(duì)象的方法,所以重寫基類的__new__方法,以此來保證創(chuàng)建對(duì)象的時(shí)候只生成一個(gè)實(shí)例
class Singleton(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance class Foo(Singleton): pass foo1 = Foo() foo2 = Foo() print foo1 is foo2 # True
方法三:使用元類
元類(參考:深刻理解Python中的元類)是用于創(chuàng)建類對(duì)象的類,類對(duì)象創(chuàng)建實(shí)例對(duì)象時(shí)一定會(huì)調(diào)用__call__方法,因此在調(diào)用__call__時(shí)候保證始終只創(chuàng)建一個(gè)實(shí)例即可,type是python中的一個(gè)元類。
class Singleton(type): def __call__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super(Singleton, cls).__call__(*args, **kwargs) return cls._instance class Foo(object): __metaclass__ = Singleton foo1 = Foo() foo2 = Foo() print foo1 is foo2 # True
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python 實(shí)現(xiàn)單例模式的5種方法
- Python單例模式的四種創(chuàng)建方式實(shí)例解析
- python單例模式原理與創(chuàng)建方法實(shí)例分析
- python單例模式的多種實(shí)現(xiàn)方法
- 聊聊python里如何用Borg pattern實(shí)現(xiàn)的單例模式
- Python下簡(jiǎn)易的單例模式詳解
- Python中實(shí)現(xiàn)單例模式的n種方式和原理
- python單例模式獲取IP代理的方法詳解
- Python中單例模式總結(jié)
- Python單例模式實(shí)例詳解
- python 6種方法實(shí)現(xiàn)單例模式
相關(guān)文章
Python如何快速上手? 快速掌握一門新語(yǔ)言的方法
Python如何快速上手? 這篇文章主要為大家詳細(xì)介紹了快速掌握一門新語(yǔ)言的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11淺析Python 中的 WSGI 接口和 WSGI 服務(wù)的運(yùn)行
這篇文章主要介紹了Python 中的 WSGI 接口和 WSGI 服務(wù)的相關(guān)資料,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12wxPython電子表格功能wx.grid實(shí)例教程
這篇文章主要介紹了wxPython電子表格功能wx.grid實(shí)例教程,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11pycharm2021激活碼使用教程(永久激活親測(cè)可用)
pycharm2021激活碼是一個(gè)可以輕松幫助用戶免費(fèi)激活pycharm2021.1軟件的文件,雖然說pycharm現(xiàn)在只是推出了2021.1的EAP版,但是如果你想先率先體驗(yàn)一波,那么就可以利用小編提供的這個(gè)激活碼來進(jìn)行使用啦,并這個(gè)激活碼是永久有效的2021-03-03Python使用matplotlib給柱狀圖添加數(shù)據(jù)標(biāo)簽bar_label()
這篇文章主要介紹了Python使用matplotlib給柱狀圖添加數(shù)據(jù)標(biāo)簽bar_label(),記錄如何用使用matplotlib給柱狀圖添加數(shù)據(jù)標(biāo)簽,是以matplotlib.pyplot.bar_label()為例,需要的朋友可以參考一下2022-03-03詳解python實(shí)現(xiàn)讀取郵件數(shù)據(jù)并下載附件的實(shí)例
這篇文章主要介紹了詳解python讀取郵件數(shù)據(jù)并下載附件的實(shí)例的相關(guān)資料,這里提供實(shí)現(xiàn)實(shí)例,幫助大家學(xué)習(xí)理解這部分內(nèi)容,需要的朋友可以參考下2017-08-08pycharm連接虛擬機(jī)的實(shí)現(xiàn)步驟
本文主要介紹了pycharm連接虛擬機(jī)的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-12-12