Python使用metaclass實(shí)現(xiàn)Singleton模式的方法
更新時(shí)間:2015年05月05日 10:41:52 作者:鴣斑兔
這篇文章主要介紹了Python使用metaclass實(shí)現(xiàn)Singleton模式的方法,實(shí)例分析了Python基于metaclass實(shí)現(xiàn)單例模式的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(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)文章
使用keras內(nèi)置的模型進(jìn)行圖片預(yù)測(cè)實(shí)例
這篇文章主要介紹了使用keras內(nèi)置的模型進(jìn)行圖片預(yù)測(cè)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Python實(shí)現(xiàn)檢測(cè)文件的MD5值來(lái)查找重復(fù)文件案例
這篇文章主要介紹了Python實(shí)現(xiàn)檢測(cè)文件的MD5值來(lái)查找重復(fù)文件案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
python-pymysql如何實(shí)現(xiàn)更新mysql表中任意字段數(shù)據(jù)
這篇文章主要介紹了python-pymysql如何實(shí)現(xiàn)更新mysql表中任意字段數(shù)據(jù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
python實(shí)現(xiàn)最短路徑的實(shí)例方法
在本篇內(nèi)容里小編給大家整理的是關(guān)于python實(shí)現(xiàn)最短路徑的實(shí)例方法,有需要的朋友們可以參考下。2020-07-07
python中while和for的區(qū)別總結(jié)
在本篇內(nèi)容里小編給大家分享的是關(guān)于python中while和for的區(qū)別以及相關(guān)知識(shí)點(diǎn),需要的朋友們可以學(xué)習(xí)下。2019-06-06

