Python下singleton模式的实现方法

yipeiwu_com6年前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

相关文章

pycharm配置当鼠标悬停时快速提示方法参数

pycharm配置当鼠标悬停时快速提示方法参数

1、配置pycharm 依次点击"File"-->"Settings",进入"Editor"-->"General",勾选"Other"下的“Show quick docum...

Python读取指定日期邮件的实例

背景:9月份有部分数据缺失,这部分数据在邮箱里,需要重新拉取,但是每天几百封邮件,总共有6、7万封邮件,使用stat()和retr(which)结合遍历很 耗时 基于如上背景,初始大致思...

完美解决Pycharm无法导入包的问题 Unresolved reference

完美解决Pycharm无法导入包的问题 Unresolved reference

如下所示: Unresolved reference 'ERROR_CODE_INPUT_ERROR' less... (Ctrl+F1) This inspection dete...

Windows平台Python编程必会模块之pywin32介绍

Windows平台Python编程必会模块之pywin32介绍

在Windows平台上,从原来使用C/C++编写原生EXE程序,到使用Python编写一些常用脚本程序,成熟的模块的使用使得编程效率大大提高了。 不过,python模块虽多,也不可能满足...

Python3多目标赋值及共享引用注意事项

Python中多目标赋值即将等号左边所有的变量名都赋值给右边的对象,完成赋值操作,比如将三个变量同时赋值给一个字符串。 a = b = c = 'Python' print(a) p...