Python使用metaclass實現(xiàn)Singleton模式的方法
更新時間:2015年05月05日 10:41:52 作者:鴣斑兔
這篇文章主要介紹了Python使用metaclass實現(xiàn)Singleton模式的方法,實例分析了Python基于metaclass實現(xiàn)單例模式的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了Python使用metaclass實現(xiàn)Singleton模式的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
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 def __new__(cls, *args, **kwargs): print "Cache new" return object.__new__(cls, *args, **kwargs) def __init__(cls, *args, **kwargs): print "Cache init" def __call__(cls, *args, **kwargs): print "Cache call" print Cache() print Cache()
輸出:
Singleton new Singleton init Singleton call Cache new Cache init <__main__.Cache object at 0x01CDB130> Singleton call <__main__.Cache object at 0x01CDB130>
希望本文所述對大家的Python程序設(shè)計有所幫助。
您可能感興趣的文章:
- Python黑魔法遠程控制開機的實例
- Python黑魔法@property裝飾器的使用技巧解析
- Python黑魔法Descriptor描述符的實例解析
- python黑魔法之參數(shù)傳遞
- python黑魔法之編碼轉(zhuǎn)換
- 詳解python metaclass(元類)
- python中metaclass原理與用法詳解
- Python探索之Metaclass初步了解
- 舉例講解Python中metaclass元類的創(chuàng)建與使用
- 詳解python單例模式與metaclass
- Python中的Classes和Metaclasses詳解
- 深入理解Python中的元類(metaclass)
- Python黑魔法之metaclass詳情
相關(guān)文章
python讀取excel指定列數(shù)據(jù)并寫入到新的excel方法
今天小編就為大家分享一篇python讀取excel指定列數(shù)據(jù)并寫入到新的excel方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07Python輸出由1,2,3,4組成的互不相同且無重復(fù)的三位數(shù)
這篇文章主要介紹了Python輸出由1,2,3,4組成的互不相同且無重復(fù)的三位數(shù),分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02Python二叉樹的遍歷操作示例【前序遍歷,中序遍歷,后序遍歷,層序遍歷】
這篇文章主要介紹了Python二叉樹的遍歷操作,結(jié)合實例形式分析了Python針對二叉樹的前序遍歷,中序遍歷,后序遍歷,層序遍歷等相關(guān)操作實現(xiàn)技巧,需要的朋友可以參考下2018-12-12python 進階學(xué)習(xí)之python裝飾器小結(jié)
這篇文章主要介紹了python 進階學(xué)習(xí)之python裝飾器小結(jié),本文通過場景分析給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09