Python下简易的单例模式详解(转)

Python 下的单例模式

要点:

  1. 1.某个类只能有一个实例;
  2. 2.它必须自行创建这个实例;
  3. 3.它必须自行向整个系统提供这个实例

方法:重写new函数

应该考虑的情况:

  1. 1.这个单例的类可能继承了别的类
  2. 2.这个单例的类还有可能要接收参数来实例化

要点:

实例化的过程其实不是直接调用init的,首先是new分配一块空间来创建实例,再由init对这个实例进行初始化.我们无法阻止new和init的调用,我们只能是限制他们的内容,以此使他们能达到单例的目的

代码:

?


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

class people(object):

    def __new__(cls,*args,**kargs):

        return super(people,cls).__new__(cls)

    def __init__(self,name):

        self.name = name

        

    def talk(self):

        print("hello,I am %s" %self.name)

    

    

    

class student(people):

    def __new__(cls,*args,**kargs):

        if not hasattr(cls,"instance"):

            

            cls.instance = super(student,cls).__new__(cls,*args,**kargs)

        return cls.instance

a = student("Timo")

print(a)

b = student("kysa")

c = student("Luyi")

a.talk()

b.talk()

print(c)

这里的输出结果是:

<__main__.student object at 0x0000025AC48BF2E8>
hello,I am Luyi
hello,I am Luyi
<__main__.student object at 0x0000025AC48BF2E8>

可以确定的是: 确实是单例了,因为a的id和b,c的id是一致的

但是为什么:a先创建明明是Timo,可是为什么a的name变成了Luyi呢?

原因:
虽然确实是a这个实例,但是在最后c重新调用了new,返回了a的实例,再经过init,改变了a的属性,执行时name ->Luyi.

解决:
这种情况下,我们只需要设置类变量,让init在类变量的限制下,只对类进行一次有效的初始化.

代码:

?


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

class people(object):

    def __new__(cls,*args,**kargs):

        return super(people,cls).__new__(cls)

    def __init__(self,name):

        self.name = name

        

    def talk(self):

        print("hello,I am %s" %self.name)

    

    

    

class student(people):

    def __new__(cls,*args,**kargs):

        if not hasattr(cls,"instance"):

            cls.instance = super(student,cls).__new__(cls,*args,**kargs)

        return cls.instance

    def __init__(self,name):

        if not hasattr(self,"init_fir"):

            self.init_fir = True

            super(student,self).__init__(name)

a = student("Timo")

print(a)

b = student("kysa")

c = student("Luyi")

a.talk()

b.talk()

print(c)

好了,到这里就用Python实现了一个简易的单例模式.

原文地址:https://www.cnblogs.com/niucunguo/p/11507364.html

时间: 2024-07-31 13:43:04

Python下简易的单例模式详解(转)的相关文章

windows下eclipse调试hadoop详解

1)下载Eclipse http://www.eclipse.org/downloads/ Eclipse Standard 4.3.2 64位 2) 下载hadoop版本对应的eclipse插件 我的hadoop是1.0.4,因此下载hadoop-eclipse-plugin-1.0.4.jar 下载地址:http://download.csdn.net/detail/m_star_jy_sy/7376169 3)安装hadoop插件 将hadoop-eclipse-plugin-1.0.4.

CentOS下安装Apache步骤详解

CentOS下安装Apache步骤详解 一.实验环境 Linux: CentOS release 6.7 (Final) Apache: httpd-2.4.23.tar.gz VMware: VMware 10.0 宿主机: Win10 x64 二.Apache介绍 Apache一款 Web服务器软件.它可以运行在几乎所有广泛使用的计算机平台上,由于其跨平台和安全性被广泛使用,是最流行的Web服务器端软件之一.它快速.可靠并且可通过简单的API扩充,将Perl/Python等解释器编译到服务器

Python安装、配置图文详解

原文地址:http://weixiaolu.iteye.com/blog/1617440 目录: 一. Python简介 二. 安装python 1. 在windows下安装 2. 在Linux下安装 三. 在windows下配置python集成开发环境(IDE) 1. 在Eclipse中安装PyDev插件 2. 配置Python Interpreters 四. 创建Python Project 五. 编写HelloWorld 六. 小结 一. Python简介: Python在Linux.wi

Python安装、配置图文详解(转载)

Python安装.配置图文详解 目录: 一. Python简介 二. 安装python 1. 在windows下安装 2. 在Linux下安装 三. 在windows下配置python集成开发环境(IDE) 1. 在Eclipse中安装PyDev插件 2. 配置Python Interpreters 四. 创建Python Project 五. 编写HelloWorld 六. 小结 一. Python简介: Python在Linux.windows.Mac os等操作系统下都有相应的版本,不管在

Python中的高级数据结构详解

这篇文章主要介绍了Python中的高级数据结构详解,本文讲解了Collection.Array.Heapq.Bisect.Weakref.Copy以及Pprint这些数据结构的用法,需要的朋友可以参考下 数据结构 数据结构的概念很好理解,就是用来将数据组织在一起的结构.换句话说,数据结构是用来存储一系列关联数据的东西.在Python中有四种内建的数据结构,分别是List.Tuple.Dictionary以及Set.大部分的应用程序不需要其他类型的数据结构,但若是真需要也有很多高级数据结构可供选择

python命名空间与闭包函数详解

python命名空间与闭包函数详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 本篇博客主要介绍的知识点如下: 1>.三元运算 2>.命名空间 3>.global与nonlocal 4>.函数即变量 5>.嵌套函数 6>.闭包函数 一.三元运算 1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yi

Python中标准模块importlib详解

Python中标准模块importlib详解 模块简介 Python提供了importlib包作为标准库的一部分.目的就是提供Python中import语句的实现(以及__import__函数).另外,importlib允许程序员创建他们自定义的对象,可用于引入过程(也称为importer). 什么是imp? 另外有一个叫做imp的模块,它提供给Python import语句机制的接口.这个模块在Python 3.4中被否决,目的就是为了只使用importlib. 这个模块有些复杂,因此我们在这

Python中self的用法详解,或者总是提示:TypeError: add() missing 1 required positional argument: &#39;self&#39;的问题解决

https://blog.csdn.net/songlh1234/article/details/83587086 下面总结一下self的用法详解,大家可以访问,可以针对平时踩过的坑更深入的了解下. https://blog.csdn.net/CLHugh/article/details/75000104, Python中self的用法详解,或者总是提示:TypeError: add() missing 1 required positional argument: 'self'的问题解决 原文

9种Java单例模式详解(推荐)

单例模式的特点 一个类只允许产生一个实例化对象. 单例类构造方法私有化,不允许外部创建对象. 单例类向外提供静态方法,调用方法返回内部创建的实例化对象.  懒汉式(线程不安全) 其主要表现在单例类在外部需要创建实例化对象时再进行实例化,进而达到Lazy Loading 的效果. 通过静态方法 getSingleton() 和private 权限构造方法为创建一个实例化对象提供唯一的途径. 不足:未考虑到多线程的情况下可能会存在多个访问者同时访问,发生构造出多个对象的问题,所以在多线程下不可用这种