Python下简易的单例模式详解

yipeiwu_com5年前Python基础

Python 下的单例模式

要点:

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

方法:重写new函数

应该考虑的情况:

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

要点:

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

代码:

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在类变量的限制下,只对类进行一次有效的初始化.

代码:

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实现了一个简易的单例模式.

以上所述是小编给大家介绍的Python下简易的单例模式详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

详解Django框架中用context来解析模板的方法

你需要一段context来解析模板。 一般情况下,这是一个 django.template.Context 的实例,不过在Django中还可以用一个特殊的子类, django.templ...

Python中动态检测编码chardet的使用教程

前言 在互联网的世界里,每个页面都使用了编码,但是形形色色的编码让我们的代码何以得知其棉麻格式呢?charset将很好的解决这个问题。 1. chardet chardet是Pytho...

pyqt5 禁止窗口最大化和禁止窗口拉伸的方法

如下所示: 在def __init__(self):函数里添加 self.setFixedSize(self.width(), self.height()) 以上这篇pyqt5 禁止窗口...

在VS2017中用C#调用python脚本的实现

情景是这样的:在C#中调用python脚本进行post请求,python脚本中使用了requests包。 Python的开发环境我们有比较多的选择,pycharm、sublime tex...

Zookeeper接口kazoo实例解析

本文主要研究的是Zookeeper接口kazoo的相关内容,具体介绍如下。 zookeeper的开发接口以前主要以java和c为主,随着python项目越来越多的使用zookeeper作...