加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 教程 > 正文

最简单的Python singleton模式达成

发布时间:2021-11-25 18:57:15 所属栏目:教程 来源:互联网
导读:最简单的Python singleton模式实现-- 用 decorator 实现 singleton 模式 刚开始学 Python 时,曾考虑过像 c++ 那样来实现 singleton 模式,但后来发现 c++ 是 c++,Python 是 Python,不能简单进行模仿。 Python 中常见的方法是借助 global 变量,或者 class
最简单的Python singleton模式实现-- 用 decorator 实现 singleton 模式
 
刚开始学 Python 时,曾考虑过像 c++ 那样来实现 singleton 模式,但后来发现 c++ 是 c++,Python 是 Python,不能简单进行模仿。
 
Python 中常见的方法是借助 global 变量,或者 class 变量来实现单件。下面介绍用 decorator 来实现:
 
##----------------------- 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
 
#@singleton ##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

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读