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