标签:nis finish instance pre self rgs code 实例 nbsp
1.在python中,单例模式是很容易实现的,随便翻翻网上的相关教程,就能够找到很多答案。
比如这样:
class hello(object):
def __new__(cls, *args, **kwargs):
if not ‘_instance_one‘ in vars(cls):
cls._instance_one=object.__new__(cls)
return cls._instance_one
return cls._instance_one
def __init__(self):
print self
a=hello()
b=hello()
#************************** result *******************************
<__main__.hello object at 0x7f8afeaf1150>
<__main__.hello object at 0x7f8afeaf1150>
Process finished with exit code 0
可以看到,两个实例的内存地址相同,即表示二者是同一个实例 。
注意:如果我们重写__new__函数的话,需要继承object类。
2.需要注意到的是 上例中的self和cls._instance_one实际是同一个东西,我们可以简单做一个测试一下:
class hello(object):
def __new__(cls, *args, **kwargs):
if not ‘_instance_one‘ in vars(cls):
cls._instance_one=object.__new__(cls)
print cls._instance_one
return cls._instance_one
return cls._instance_one
def __init__(self):
print self
a=hello()
#************************************** result **********************************
<__main__.hello object at 0x7fb31f65e150>
<__main__.hello object at 0x7fb31f65e150>
Process finished with exit code 0
3.如果我们需要让单例模式只初始化一次的话,我们只需要加一个标志即可:
class hello(object):
def __new__(cls, *args, **kwargs):
if not ‘_instance_one‘ in vars(cls):
cls._instance_one=object.__new__(cls)
cls._instance_one._flag=1
return cls._instance_one
return cls._instance_one
def __init__(self):
if self._flag:
print self
self._flag=0
print "end"
a=hello()
b=hello()
#************************************result*********************************
<__main__.hello object at 0x7f14de3bd150>
end
end
4.注意到上例中的_flag写在类内,类外都可以,我们同样可以做一个实验:
class hello(object):
_flag=1
def __new__(cls, *args, **kwargs):
if not ‘_instance_one‘ in vars(cls):
cls._instance_one=object.__new__(cls)
return cls._instance_one
if not ‘_instance_two‘ in vars(cls):
cls._instance_two=object.__new__(cls)
return cls._instance_two
def __init__(self):
print self._flag
self._flag=0
print self._flag
a=hello()
b=hello()
#*************************************result ***************************************
1
0
1
0
Process finished with exit code 0
可以看到二者是等价的。
标签:nis finish instance pre self rgs code 实例 nbsp
原文地址:https://www.cnblogs.com/lomooo/p/8846755.html