Python使用metaclass實(shí)現(xiàn)Singleton模式的方法
本文實(shí)例講述了Python使用metaclass實(shí)現(xiàn)Singleton模式的方法。分享給大家供大家參考。具體實(shí)現(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>
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
- Python黑魔法遠(yuǎn)程控制開機(jī)的實(shí)例
- Python黑魔法@property裝飾器的使用技巧解析
- Python黑魔法Descriptor描述符的實(shí)例解析
- 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)文章
TensorFlow中權(quán)重的隨機(jī)初始化的方法
本篇文章主要介紹了TensorFlow中權(quán)重的隨機(jī)初始化的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-02-02
python讀取excel指定列數(shù)據(jù)并寫入到新的excel方法
今天小編就為大家分享一篇python讀取excel指定列數(shù)據(jù)并寫入到新的excel方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Python簡單實(shí)現(xiàn)enum功能的方法
這篇文章主要介紹了Python簡單實(shí)現(xiàn)enum功能的方法,簡單分析了Python實(shí)現(xiàn)enum功能的相關(guān)技巧,需要的朋友可以參考下2016-04-04
Python輸出由1,2,3,4組成的互不相同且無重復(fù)的三位數(shù)
這篇文章主要介紹了Python輸出由1,2,3,4組成的互不相同且無重復(fù)的三位數(shù),分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
Python二叉樹的遍歷操作示例【前序遍歷,中序遍歷,后序遍歷,層序遍歷】
這篇文章主要介紹了Python二叉樹的遍歷操作,結(jié)合實(shí)例形式分析了Python針對(duì)二叉樹的前序遍歷,中序遍歷,后序遍歷,層序遍歷等相關(guān)操作實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-12-12
python 進(jìn)階學(xué)習(xí)之python裝飾器小結(jié)
這篇文章主要介紹了python 進(jìn)階學(xué)習(xí)之python裝飾器小結(jié),本文通過場景分析給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09

