python-day30(正式学习)
单例模式
什么是单例模式
- 单例模式:基于某种方法实例化多次得到实例是同一个
为什么用单例模式
- 当实例化多次得到的对象中存放的属性都一样的情况,应该将多个对象指向同一个内存,即同一个实例
用类方法来实现单例模式
# 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(正式学习)的更多相关文章
- Python 装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...
- Requests:Python HTTP Module学习笔记(一)(转)
Requests:Python HTTP Module学习笔记(一) 在学习用python写爬虫的时候用到了Requests这个Http网络库,这个库简单好用并且功能强大,完全可以代替python的标 ...
- 从Theano到Lasagne:基于Python的深度学习的框架和库
从Theano到Lasagne:基于Python的深度学习的框架和库 摘要:最近,深度神经网络以“Deep Dreams”形式在网站中如雨后春笋般出现,或是像谷歌研究原创论文中描述的那样:Incept ...
- Comprehensive learning path – Data Science in Python深入学习路径-使用python数据中学习
http://blog.csdn.net/pipisorry/article/details/44245575 关于怎么学习python,并将python用于数据科学.数据分析.机器学习中的一篇非常好 ...
- (转载)Python装饰器学习
转载出处:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方 ...
- 正式学习React(五) react-redux源码分析
磨刀不误砍柴工,咱先把react-redux里的工具函数分析一下: 源码点这里 shallowEqual.js export default function shallowEqual(objA, ...
- 正式学习React(一) 开始学习之前必读
为什么要加这个必读!因为webpack本身是基于node环境的, 里面会涉及很多路径问题,我们可能对paths怎么写!webpack又是怎么找到这些paths的很迷惑. 本文是我已经写完正式学习Rea ...
- python网络爬虫学习笔记
python网络爬虫学习笔记 By 钟桓 9月 4 2014 更新日期:9月 4 2014 文章文件夹 1. 介绍: 2. 从简单语句中開始: 3. 传送数据给server 4. HTTP头-描写叙述 ...
- Python装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 ? 1 2 3 4 5 6 7 8 # -*- ...
- Python的基础学习(第二周)
模块初始 sys模块 import sys sys.path #打印环境变量 sys.argv#打印该文件路径 #注意:该文件名字不能跟导入模块名字相同 os模块 import os cmd_res ...
随机推荐
- Count the Buildings
K - Count the Buildings 参考:Count the Buildings 思路可以借鉴,但是代码略有问题 写的时候 re 了 9 发,然后把变量定义的顺序换了一下居然 A 了,以为 ...
- docker之CPU配额参数的混合使用
在启动容器的时候有很多参数,这里来实践一下与CPU相关的参数. 实例: 创建两个容器,docker10.docker20,让两个容器只运行在CPU0上,然后测试CPU使用率. [root@openst ...
- Inter IPP & Opencv + codeblocks 在centos 环境下的配置
一.先安装codeblocks wget http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-12.noar ...
- python接口自动化:python3.6中import Crypto.Hash报错的解决方案
一:问题 python3.6中算法加密引入包Crypto报错,即便安装了: pip install crypto pip install pycrypto pip install pycryptodo ...
- JS基础_对象操作
1.in 运算符 通过该运算符可以检查一个对象中是否含有指定的属性,如果有,返回true 语法: “属性名” in 对象 var obj = { name:"hello" } co ...
- 4 Java 选择排序
1 基本思想 在未排序序列中找到最小元素,存放到未排序序列的起始位置.在所有的完全依靠交换去移动元素的排序方法中,选择排序属于非常好的一种算法,需要对比len-n-1次,但是只交换1次或者0次. 2 ...
- LeetCode 136. 只出现一次的数字(Single Number)
题目描述 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次.找出那个只出现了一次的元素. 说明: 你的算法应该具有线性时间复杂度. 你可以不使用额外空间来实现吗? 示例 1: ...
- 类 kotlin(13)
Kotlin 中使用关键字 class 声明类class Invoice {} 类声明由类名.类头(指定其类型参数.主 构造函数等) 和由大括号包围的类体构成.类头和类体都是可选的:如果一个类没有类体 ...
- flutter 打包
iOS打包 iOS打包需要注意一下一些设置 info.plist 设置ATS.白名单.字符串等等 Assets.xcassets 替换icon,替换LaunchImage中内容 注意LaunchIma ...
- mysql 安装 和 mysql 远程连接
一.mysql安装 1.下载MySQL数据库可以访问官方网站:https://www.mysql.com/ 2.点击DOWNLOADS模块下的Community模块下的MySQL Community ...