Python下singleton模式的實(shí)現(xiàn)方法
很多開發(fā)人員在剛開始學(xué)Python 時,都考慮過像 c++ 那樣來實(shí)現(xiàn) singleton 模式,但后來會發(fā)現(xiàn) c++ 是 c++,Python 是 Python,不能簡單的進(jìn)行模仿。
Python 中常見的方法是借助 global 變量,或者 class 變量來實(shí)現(xiàn)單件。本文就介紹以decorator來實(shí)現(xiàn) singleton 模式的方法。示例代碼如下:
##----------------------- code begin -----------------------
# -*- coding: utf-8 -*-
def singleton(cls):
"""Define a class with a singleton instance."""
instances = {}
def getinstance(*args, **kwds):
return instances.setdefault(cls, cls(*args, **kwds))
return getinstance
##1 未來版Python支持Class Decorator時可以這樣用
class Foo(object):
def __init__(self, attr=1):
self.attr = attr
Foo = singleton( Foo ) ##2 2.5及之前版不支持Class Decorator時可以這樣用
if __name__ == "__main__":
ins1 = Foo(2) # 等效于: ins1 = singleton(Foo)(2)
print "Foo(2) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins1), ins1.attr, ('error', 'ok')[ins1.attr == 2])
ins2 = Foo(3)
print "Foo(3) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins2), ins2.attr, ('error', 'ok')[ins2.attr == 2])
ins2.attr = 5
print "ins.attr=5 -> ins.attr=%d, %s" % (ins2.attr, ('error', 'ok')[ins2.attr == 5])
##------------------------ code end ------------------------
輸出:
Foo(2) -> id(ins)=19295376, ins.attr=2, ok Foo(3) -> id(ins)=19295376, ins.attr=2, ok ins.attr=5 -> ins.attr=5, ok
相關(guān)文章
TensorFlow實(shí)現(xiàn)iris數(shù)據(jù)集線性回歸
這篇文章主要介紹了TensorFlow實(shí)現(xiàn)iris數(shù)據(jù)集線性回歸,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
python實(shí)現(xiàn)class對象轉(zhuǎn)換成json/字典的方法
這篇文章主要介紹了python實(shí)現(xiàn)class對象轉(zhuǎn)換成json/字典的方法,結(jié)合實(shí)例形式分析了Python類型轉(zhuǎn)換的相關(guān)技巧,需要的朋友可以參考下2016-03-03
基于python實(shí)現(xiàn)操作git過程代碼解析
這篇文章主要介紹了基于python實(shí)現(xiàn)操作git過程代碼解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
Python實(shí)現(xiàn)FTP上傳文件或文件夾實(shí)例(遞歸)
本篇文章主要介紹了Python實(shí)現(xiàn)FTP上傳文件或文件夾實(shí)例(遞歸),具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01
解決python多線程報(bào)錯:AttributeError: Can''t pickle local object問題
這篇文章主要介紹了解決python多線程報(bào)錯:AttributeError: Can't pickle local object問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
使用pandas中的DataFrame.rolling方法查看時間序列中的異常值
Pandas是Python中最受歡迎的數(shù)據(jù)分析和處理庫之一,提供了許多強(qiáng)大且靈活的數(shù)據(jù)操作工具,在Pandas中,DataFrame.rolling方法是一個強(qiáng)大的工具,在本文中,我們將深入探討DataFrame.rolling方法的各種參數(shù)和示例,以幫助您更好地理解和應(yīng)用這個功能2023-12-12
Python多個MP4合成視頻的實(shí)現(xiàn)方法
最近接觸了個項(xiàng)目,需要把多個文件合成一個視頻,本文主要使用Python把多個MP4合成視頻,感興趣的可以了解一下2021-07-07
python linecache 處理固定格式文本數(shù)據(jù)的方法
今天小編就為大家分享一篇python linecache 處理固定格式文本數(shù)據(jù)的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
Python自定義命令行參數(shù)選項(xiàng)和解析器
這篇文章主要介紹了Python自定義命令行參數(shù)選項(xiàng)和解析器,本文主要使用的方法為argparse.ArgumentParser(),此模塊可以讓人輕松編寫用戶友好的命令行接口,程序定義它需要的參數(shù),需要的朋友可以參考下2023-07-07

