Python下singleton模式的实现方法

yipeiwu_com5年前Python基础

很多开发人员在刚开始学Python 时,都考虑过像 c++ 那样来实现 singleton 模式,但后来会发现 c++ 是 c++,Python 是 Python,不能简单的进行模仿。

Python 中常见的方法是借助 global 变量,或者 class 变量来实现单件。本文就介绍以decorator来实现 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

相关文章

Python实现制度转换(货币,温度,长度)

人民币和美元是世界上通用的两种货币之一,写一个程序进行货币间币值转换,其中: 人民币和美元间汇率固定为:1美元 = 6.78人民币。 程序可以接受人民币或美元输入,转换为美元或人民币输出...

Request的中断和ErrorHandler实例解析

概述 在view函数中,如果需要中断request,可以使用abort(500)或者直接raise exception。当然我们还需要返回一个出错信息给前端,所以需要定制一下ErrorH...

python脚本实现音频m4a格式转成MP3格式的实例代码

python脚本实现音频m4a格式转成MP3格式的实例代码

前言 群里看到有人询问:谁会用python将微信音频文件后缀m4a格式转成mp3格式,毫不犹豫回了句:我会。 然后就私下聊起来了 解决方法介绍如下: 工具:windows系统,pytho...

python实现批量nii文件转换为png图像

之前介绍过单个nii文件转换成png图像: /post/165693.htm 这里介绍将多个nii文件(保存在一个文件夹下)转换成png图像。且图像单个文件夹的名称与nii名字相同。...

Django1.3添加app提示模块不存在的解决方法

使用Django添加应用的时候,一直提示Error: No module named myapp。意思是找不到这个名字的应用,可是我已经startapp成功,并且系统已经创建相应的目录...