python单例模式实例分析

上传人:bin****86 文档编号:59370820 上传时间:2018-11-06 格式:DOCX 页数:3 大小:15.81KB
返回 下载 相关 举报
python单例模式实例分析_第1页
第1页 / 共3页
python单例模式实例分析_第2页
第2页 / 共3页
python单例模式实例分析_第3页
第3页 / 共3页
亲,该文档总共3页,全部预览完了,如果喜欢就下载吧!
资源描述

《python单例模式实例分析》由会员分享,可在线阅读,更多相关《python单例模式实例分析(3页珍藏版)》请在金锄头文库上搜索。

1、我真正系统地接触和学习党的基本知识是在这次中级党校的培训班上。通过学习,了解了党的发展历程,对党的性质、宗旨、任务等基本知识有了进一步的了解Python单例模式实例分析本文实例讲述了Python单例模式的使用方法。分享给大家供大家参考。具体如下:方法一复制代码 代码如下:import threadingclass Singleton(object):_instance = None_lock = threading.Lock() # used to synchronize codedef _init_(self):disable the _init_ methodstaticmethoddef

2、 getInstance():if not Singleton._instance:Singleton._lock.acquire()if not Singleton._instance:Singleton._instance = object._new_(Singleton)object._init_(Singleton._instance)Singleton._lock.release()return Singleton._instance1.禁用_init_方法,不能直接创建对象。2._instance,单例对象私有化。静态方法,通过类名直接调用。4._lock,代码锁。5.继承obje

3、ct类,通过调用object的_new_方法创建单例对象,然后调用object的_init_方法完整初始化。6.双重检查加锁,既可实现线程安全,又使性能不受很大影响。方法二:使用decorator复制代码 代码如下:#encoding=utf-8def singleton(cls):instances = def getInstance():if cls not in instances:instancescls = cls()return instancesclsreturn getInstancesingletonclass SingletonClass:passif _name_ = _

4、main_:s = SingletonClass()s2 = SingletonClass()print sprint s2也应该加上线程安全复制代码 代码如下:import threadingclass Sing(object):def _init_():disable the _init_ method_inst = None # make it so-called private_lock = threading.Lock() # used to synchronize codestaticmethoddef getInst():Sing._lock.acquire()if not Sing._inst:Sing._inst = object._new_(Sing)object._init_(Sing._inst)Sing._lock.release()return Sing._inst希望本文所述对大家的Python程序设计有所帮助。对党的认识也有了进一步的提高。才真正体会到了中国共产党的伟大、光荣和正确,更感到只有中国共产党是全中国最广大人民利益的忠实代表

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 办公文档 > 总结/报告

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号