简单了解python单例模式的几种写法


Posted in Python onJuly 01, 2019

方法一:使用装饰器

装饰器维护一个字典对象instances,缓存了所有单例类,只要单例不存在则创建,已经存在直接返回该实例对象。

def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class Foo(object):
pass
foo1 = Foo()
foo2 = Foo()
print foo1 is foo2

方法二:使用基类

__new__是真正创建实例对象的方法,所以重写基类的__new__方法,以此来保证创建对象的时候只生成一个实例

class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class Foo(Singleton):
pass
foo1 = Foo()
foo2 = Foo()
print foo1 is foo2 # True

方法三:使用元类

元类(参考:深刻理解Python中的元类)是用于创建类对象的类,类对象创建实例对象时一定会调用__call__方法,因此在调用__call__时候保证始终只创建一个实例即可,type是python中的一个元类。

class Singleton(type):
def __call__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance
class Foo(object):
__metaclass__ = Singleton
foo1 = Foo()
foo2 = Foo()
print foo1 is foo2 # True

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python获取外网IP并发邮件的实现方法
Oct 01 Python
python实现读取excel写入mysql的小工具详解
Nov 20 Python
Sanic框架应用部署方法详解
Jul 18 Python
用python3教你任意Html主内容提取功能
Nov 05 Python
Python图像处理之图像的缩放、旋转与翻转实现方法示例
Jan 04 Python
使用Python和Prometheus跟踪天气的使用方法
May 06 Python
Python+Selenium使用Page Object实现页面自动化测试
Jul 14 Python
django-初始配置(纯手写)详解
Jul 30 Python
Ubuntu下Python+Flask分分钟搭建自己的服务器教程
Nov 19 Python
ansible动态Inventory主机清单配置遇到的坑
Jan 19 Python
python GUI库图形界面开发之PyQt5滑块条控件QSlider详细使用方法与实例
Feb 28 Python
Python Numpy之linspace用法说明
Apr 17 Python
python如何获取列表中每个元素的下标位置
Jul 01 #Python
Django自定义用户登录认证示例代码
Jun 30 #Python
Python中栈、队列与优先级队列的实现方法
Jun 30 #Python
Python中请不要再用re.compile了
Jun 30 #Python
用python求一个数组的和与平均值的实现方法
Jun 29 #Python
Python:Numpy 求平均向量的实例
Jun 29 #Python
python 计算数据偏差和峰度的方法
Jun 29 #Python
You might like
PHP CURL获取返回值的方法
2014/05/04 PHP
一个经典实用的PHP图像处理类分享
2014/11/18 PHP
java解析json方法总结
2019/05/16 PHP
html下载本地
2006/06/19 Javascript
javascript中setAttribute()函数使用方法及兼容性
2015/07/19 Javascript
jquery简单实现幻灯片的方法
2015/08/03 Javascript
AngularJS使用ng-options指令实现下拉框
2016/08/23 Javascript
JS高仿抛物线加入购物车特效实现代码
2017/02/20 Javascript
Vue 创建组件的两种方法小结(必看)
2018/02/23 Javascript
node结合swig渲染摸板的方法
2018/04/11 Javascript
React组件重构之嵌套+继承及高阶组件详解
2018/07/19 Javascript
详解使用create-react-app添加css modules、sasss和antd
2018/07/31 Javascript
提升node.js中使用redis的性能遇到的问题及解决方法
2018/10/30 Javascript
Nuxt.js开启SSR渲染的教程详解
2018/11/30 Javascript
vue form check 表单验证的实现代码
2018/12/09 Javascript
vue 中this.$set 动态绑定数据的案例讲解
2021/01/29 Vue.js
[02:18]DOTA2英雄基础教程 育母蜘蛛
2014/01/20 DOTA
[05:31]干嘛呢兄弟!DOTA2 TI9语音轮盘部分出处
2019/05/14 DOTA
python使用os模块的os.walk遍历文件夹示例
2014/01/27 Python
Python的Scrapy爬虫框架简单学习笔记
2016/01/20 Python
深入理解Python装饰器
2016/07/27 Python
Python语言实现百度语音识别API的使用实例
2017/12/13 Python
python和pygame实现简单俄罗斯方块游戏
2021/02/19 Python
python代码编写计算器小程序
2020/03/30 Python
如何通过python实现人脸识别验证
2020/01/17 Python
python实现扫雷小游戏
2020/04/24 Python
PyCharm2019 安装和配置教程详解附激活码
2020/07/31 Python
捷克浴室和厨房设备购物网站:SIKO
2018/08/11 全球购物
绘儿乐产品官方在线商店:Crayola.com
2019/09/07 全球购物
春节活动策划方案
2014/01/24 职场文书
中学劳技课教师的自我评价
2014/02/05 职场文书
知名企业招聘广告词大全
2014/03/18 职场文书
销售2014年度工作总结
2014/12/08 职场文书
十佳少年事迹材料
2014/12/25 职场文书
python区块链实现简版工作量证明
2022/05/25 Python
Qt数据库应用之实现图片转pdf
2022/06/01 Java/Android