簡單了解python單例模式的幾種寫法
方法一:使用裝飾器
裝飾器維護一個字典對象instances,緩存了所有單例類,只要單例不存在則創(chuàng)建,已經(jīng)存在直接返回該實例對象。
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)建實例對象的方法,所以重寫基類的__new__方法,以此來保證創(chuàng)建對象的時候只生成一個實例
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)建類對象的類,類對象創(chuàng)建實例對象時一定會調(diào)用__call__方法,因此在調(diào)用__call__時候保證始終只創(chuàng)建一個實例即可,type是python中的一個元類。
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
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺析Python 中的 WSGI 接口和 WSGI 服務(wù)的運行
這篇文章主要介紹了Python 中的 WSGI 接口和 WSGI 服務(wù)的相關(guān)資料,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12Python使用matplotlib給柱狀圖添加數(shù)據(jù)標簽bar_label()
這篇文章主要介紹了Python使用matplotlib給柱狀圖添加數(shù)據(jù)標簽bar_label(),記錄如何用使用matplotlib給柱狀圖添加數(shù)據(jù)標簽,是以matplotlib.pyplot.bar_label()為例,需要的朋友可以參考一下2022-03-03詳解python實現(xiàn)讀取郵件數(shù)據(jù)并下載附件的實例
這篇文章主要介紹了詳解python讀取郵件數(shù)據(jù)并下載附件的實例的相關(guān)資料,這里提供實現(xiàn)實例,幫助大家學習理解這部分內(nèi)容,需要的朋友可以參考下2017-08-08