一、什么是单例模式

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

二、为什么用单例模式

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

三、单例模式(类内部定义静态方法)

# 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 __new__ 实现单例模式 python经典面试题的更多相关文章

  1. Python 经典面试题汇总之基础篇

    基础篇 1:为什么学习Python 公司建议使用Python,然后自己通过百度和向有学过Python的同学了解了Python.Python这门语言,入门比较简单,它简单易学,生态圈比较强大,涉及的地方 ...

  2. [ZZ]知名互联网公司Python的16道经典面试题及答案

    知名互联网公司Python的16道经典面试题及答案 https://mp.weixin.qq.com/s/To0kYQk6ivYL1Lr8aGlEUw 知名互联网公司Python的16道经典面试题及答 ...

  3. python的一些基本概念知识和面试题

    对于机器学习算法工程师而言,Python是不可或缺的语言,它的优美与简洁令人无法自拔.那么你了解过Python编程面试题吗?从Python基础到网页爬虫你是否能全方位Hold住?今天,机器之心为读者们 ...

  4. Python学习笔记之在Python中实现单例模式

    有些时候你的项目中难免需要一些全局唯一的对象,这些对象大多是一些工具性的东西,在Python中实现单例模式并不是什么难事.以下总结几种方法: 使用类装饰器 使用装饰器实现单例类的时候,类本身并不知道自 ...

  5. python 四种单例模式

    1 使用__new__方法 Python class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_i ...

  6. python __new__以及__init__

    @[深入Python]__new__和__init__ 1 2 3 4 5 6 7 8 class A(object):     def __init__(self):         print & ...

  7. python设计模式之单例模式(一)

    前言 单例模式是创建模式中比较常见和常用的模式,在程序执行的整个生命周期只存在一个实例对象. 系列文章 python设计模式之单例模式(一) python设计模式之常用创建模式总结(二) python ...

  8. python设计模式之单例模式(二)

    上次我们简单了解了一下什么是单例模式,今天我们继续探究.上次的内容点这 python设计模式之单例模式(一) 上次们讨论的是GoF的单例设计模式,该模式是指:一个类有且只有一个对象.通常我们需要的是让 ...

  9. python设计模式之单例模式(一)

    单例设计模式的概念: 单例设计模式即确保类有且只有一个特定类型的对象,并提供全局访问点.一般我们操作数据库的时候为了避免统一资源产生互相冲突,创建单例模式可以维护数据的唯一性. 单例模式的特性: 确保 ...

随机推荐

  1. ASP.NET MVC 执行流程介绍

    Routing 组件   Controller   Controller中可用的ActionResult MVC-View(使用的抽象工厂模式的视图引擎) 视图模型

  2. 记忆(缓存)函数返回值:Python 实现

    对于经常调用的函数,特别是递归函数或计算密集的函数,记忆(缓存)返回值可以显着提高性能.而在 Python 里,可以使用字典来完成. 例子:斐波那契数列 下面这个计算斐波那契数列的函数 fib() 具 ...

  3. 课堂小记---JavaScript(3)

    操作DOM var newDOM=DOM元素.cloneNode(参数); 克隆(复制)当前节点,参数默认为false只复制当前节点元素.参数为true时复制当前元素及其后代和所有属性. day06 ...

  4. linux 端口占用

    进程id为9106,进程名称为java的进程,占用了8080端口(监听了8080端口)

  5. Axure RP 8 软件介绍

    介绍 此软件可以用于制作快速原型,也可以绘制中保真原型草图. 应用人群:产品经理.交互设计师.UI设计师.网页设计师. 原型分类:低保真(手绘草图).中保真(使用相关软件绘制出来的).高保真(包含效果 ...

  6. npm 安装cnpm淘宝镜像时报错解决

    详细报错 D:\workspace\es61> npm install -g cnpm --registry=https://registry.npm.taobao.org npm WARN d ...

  7. Codeforces 1144F Graph Without Long Directed Paths (DFS染色+构造)

    <题目链接> 题目大意:给定一个无向图,该无向图不含自环,且无重边.现在要你将这个无向图定向,使得不存在任何一条路径长度大于等于2.然后根输入边的顺序,输出构造的有向图.如果构造的边与输入 ...

  8. Python 判断文件后缀

    方法1, str的endswith方法: ims_path='data/market1501/Market-1501-v15.09.15/bounding_box_test/12312.jpg' im ...

  9. 练习2-1 Programming in C is fun!

    练习2-1 Programming in C is fun! 一 问题描述 本题要求编写程序,输出一个短句“Programming in C is fun!”. 输入格式: 本题目没有输入. 输出格式 ...

  10. tensorflow 使用 1 常量,变量

    import tensorflow as tf #创建一个常量 op 一行二列 m1 = tf.constant([[3, 3]]) #创建一个常量 op 二行一列 m2 = tf.constant( ...