单例模式

什么是单例模式

  • 单例模式:基于某种方法实例化多次得到实例是同一个

为什么用单例模式

  • 当实例化多次得到的对象中存放的属性都一样的情况,应该将多个对象指向同一个内存,即同一个实例

用类方法来实现单例模式

# settings.py
IP = '1.1.1.1'
PORT = 3306 class Mysql:
__instacne = None def __init__(self, ip, port):
self.ip = ip
self.port = port @classmethod
def from_conf(cls):
if cls.__instacne is None:
cls.__instacne = cls(IP, PORT)
return cls.__instacne obj1 = Mysql.from_conf()
obj2 = Mysql.from_conf()
obj3 = Mysql.from_conf()
print(obj1 is obj2 is obj3)
True
print(obj1.__dict__)
print(obj2.__dict__)
print(obj3.__dict__)
{'ip': '1.1.1.1', 'port': 3306}
{'ip': '1.1.1.1', 'port': 3306}
{'ip': '1.1.1.1', 'port': 3306}
obj4 = Mysql('10.10.10.11', 3307)
print(obj4.__dict__)
{'ip': '10.10.10.11', 'port': 3307}

用装饰器实现单例模式

# settings.py
IP = '1.1.1.1'
PORT = 3306 def singleton(cls):
cls.__instance = cls(IP, PORT) def wrapper(*args, **kwargs):
if len(args) == 0 and len(kwargs) == 0:
return cls.__instance
return cls(*args, **kwargs) return wrapper @singleton # Mysql = singleton(Mysql) # Mysql = wrapper
class Mysql:
def __init__(self, ip, port):
self.ip = ip
self.port = port obj1 = Mysql() # wrapper()
obj2 = Mysql() # wrapper()
obj3 = Mysql() # wrapper()
print(obj1 is obj2 is obj3)
True
print(obj1.__dict__)
print(obj2.__dict__)
print(obj3.__dict__)
{'ip': '1.1.1.1', 'port': 3306}
{'ip': '1.1.1.1', 'port': 3306}
{'ip': '1.1.1.1', 'port': 3306}
obj4 = Mysql('1.1.1.4', 3308)
print(obj4.__dict__)
{'ip': '1.1.1.4', 'port': 3308}

用元类实现单例模式

# settings.py
IP = '1.1.1.1'
PORT = 3306 class Mymeta(type):
def __init__(self, class_name, class_bases, class_dic): # self = Mysql
super(Mymeta, self).__init__(class_name, class_bases, class_dic) # 完成Mysql对象的初始化
self.__instance = self.__new__(self) # 造出一个Mysql的对象
self.__init__(self.__instance, IP, PORT) # 从配置文件中加载配置完成Mysql对象的初始化 print(self.__instance)
print(self.__instance.__dict__) def __call__(self, *args, **kwargs): # self = Mysql
if len(args) == 0 and len(kwargs) == 0:
return self.__instance obj = self.__new__(self)
self.__init__(obj, *args, **kwargs) return obj class Mysql(object, metaclass=Mymeta): # Mysql = Mymeta(...)
def __init__(self, ip, port):
self.ip = ip
self.port = port obj1 = Mysql()
obj2 = Mysql()
obj3 = Mysql()
<__main__.Mysql object at 0x10c7f1f98>
{'ip': '1.1.1.1', 'port': 3306}
print(obj1 is obj2 is obj3)
True
print(obj1.__dict__)
print(obj2.__dict__)
print(obj3.__dict__)
{'ip': '1.1.1.1', 'port': 3306}
{'ip': '1.1.1.1', 'port': 3306}
{'ip': '1.1.1.1', 'port': 3306}
obj4 = Mysql('10.10.10.11', 3308) print(obj4.__dict__)
{'ip': '10.10.10.11', 'port': 3308}
print(Mysql.__dict__)
{'__module__': '__main__', '__init__': <function Mysql.__init__ at 0x10c6b1d90>, '__dict__': <attribute '__dict__' of 'Mysql' objects>, '__weakref__': <attribute '__weakref__' of 'Mysql' objects>, '__doc__': None, '_Mymeta__instance': <__main__.Mysql object at 0x10c7f1f98>}

python-day30(正式学习)的更多相关文章

  1. Python 装饰器学习

    Python装饰器学习(九步入门)   这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...

  2. Requests:Python HTTP Module学习笔记(一)(转)

    Requests:Python HTTP Module学习笔记(一) 在学习用python写爬虫的时候用到了Requests这个Http网络库,这个库简单好用并且功能强大,完全可以代替python的标 ...

  3. 从Theano到Lasagne:基于Python的深度学习的框架和库

    从Theano到Lasagne:基于Python的深度学习的框架和库 摘要:最近,深度神经网络以“Deep Dreams”形式在网站中如雨后春笋般出现,或是像谷歌研究原创论文中描述的那样:Incept ...

  4. Comprehensive learning path – Data Science in Python深入学习路径-使用python数据中学习

    http://blog.csdn.net/pipisorry/article/details/44245575 关于怎么学习python,并将python用于数据科学.数据分析.机器学习中的一篇非常好 ...

  5. (转载)Python装饰器学习

    转载出处:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方 ...

  6. 正式学习React(五) react-redux源码分析

    磨刀不误砍柴工,咱先把react-redux里的工具函数分析一下: 源码点这里  shallowEqual.js export default function shallowEqual(objA, ...

  7. 正式学习React(一) 开始学习之前必读

    为什么要加这个必读!因为webpack本身是基于node环境的, 里面会涉及很多路径问题,我们可能对paths怎么写!webpack又是怎么找到这些paths的很迷惑. 本文是我已经写完正式学习Rea ...

  8. python网络爬虫学习笔记

    python网络爬虫学习笔记 By 钟桓 9月 4 2014 更新日期:9月 4 2014 文章文件夹 1. 介绍: 2. 从简单语句中開始: 3. 传送数据给server 4. HTTP头-描写叙述 ...

  9. Python装饰器学习

    Python装饰器学习(九步入门)   这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 ? 1 2 3 4 5 6 7 8 # -*- ...

  10. Python的基础学习(第二周)

    模块初始 sys模块 import sys sys.path #打印环境变量 sys.argv#打印该文件路径 #注意:该文件名字不能跟导入模块名字相同 os模块 import os cmd_res ...

随机推荐

  1. 部分和问题(dfs)

    部分和问题 描述 给定整数a1.a2........an,判断是否可以从中选出若干数,使它们的和恰好为K. 输入 首先,n和k,n表示数的个数,k表示数的和.接着一行n个数.(1<=n<= ...

  2. centos6.5和centos7如何搭建php环境(包括php7)

    查看下centos的版本信息: #适用于所有的linux lsb_release -a #或者 cat /etc/redhat-release #又或者 rpm -q centos-release 安 ...

  3. stingstream 类

    使用完后在使用必须要clear():

  4. VUE中让由全局变量添加生成的新数组不随全局变量的变化而变化

    问题场景: const addOptions = { singleOrComplex, totalNum: this.smallTotalPrice, selectList: this.purchas ...

  5. 微信小程序之地址联动

    这就是我们要实现的效果 <view class="consignee"> <!-- consignee 收件人 --> <text>收件人: & ...

  6. [go]beego获取参数/返回参数

    获取前端传来的参数 获取数据并转为对应的类型 - ?id=111&id=122 c.GetInt("id") int,111 - ?id=111&id=122 c. ...

  7. javascript循环语句

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. 小D课堂 - 零基础入门SpringBoot2.X到实战_第14节 高级篇幅之SpringBoot多环境配置_59、SpringBoot多环境配置介绍和项目实战

    笔记 1.SpringBoot多环境配置介绍和项目实战(核心知识)     简介:SpringBoot介绍多环境配置和使用场景 1.不同环境使用不同配置         例如数据库配置,在开发的时候, ...

  9. Git代码行数统计命令

    统计zhangsan在某个时间段内的git新增删除代码行数 git log --author=zhangsan--since=2018-01-01 --until=2019-04-01 --forma ...

  10. Servlet(3):Cookie

    概念 Cookie是存储在客户端计算机上的文本文件,并保留了各种跟踪信息.Java Servlet支持HTTP Cookie. 识别返回用户包括三个步骤: (1) 服务器脚本向浏览器发送一组Cooki ...