国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python下singleton模式的實(shí)現(xiàn)方法

2019-11-25 18:19:12
字體:
供稿:網(wǎng)友

很多開發(fā)人員在剛開始學(xué)Python 時(shí),都考慮過像 c++ 那樣來實(shí)現(xiàn) singleton 模式,但后來會(huì)發(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時(shí)可以這樣用class Foo(object):def __init__(self, attr=1):self.attr = attrFoo = singleton( Foo ) ##2 2.5及之前版不支持Class Decorator時(shí)可以這樣用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 = 5print "ins.attr=5 -> ins.attr=%d, %s" % (ins2.attr, ('error', 'ok')[ins2.attr == 5]) ##------------------------ code end ------------------------

輸出:

Foo(2) -> id(ins)=19295376, ins.attr=2, okFoo(3) -> id(ins)=19295376, ins.attr=2, okins.attr=5 -> ins.attr=5, ok
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 墨玉县| 星子县| 遵义市| 弥渡县| 伊春市| 平乐县| 潮安县| 昭苏县| 文山县| 中江县| 辛集市| 台东市| 如皋市| 洛扎县| 丰镇市| 芦溪县| 庆阳市| 虹口区| 乡宁县| 蓝山县| 财经| 舒兰市| 桃江县| 石泉县| 奇台县| 博野县| 宜兰县| 石林| 个旧市| 赤峰市| 许昌市| 德惠市| 枣庄市| 长丰县| 水城县| 化德县| 咸阳市| 林芝县| 万州区| 资溪县| 乌兰察布市|