single-case mode
As the name implies, there is only one instance, and if it exists, it does not create a
#!/usr/bin/env python
# Encoding:utf-8
class Singleton():
def __new__(Cls,*args,**kwargs) :
if notHasattr (CLS,' _inst '):
cls._inst=Super(SINGLETON,CLS). __new__(Cls,*args,**kwargs)
returnCls._inst
class A(Singleton):
def __init__(Self, s=none) :
SuperA Self). __init__()
Self. s=s
if__name__==' __main__ ':
A=a ()
B=a ()
Print (a)
Print (b)
The output can be seen as instance addresses of instances A and B
<__main__.A object at 0x02742810>
<__main__.A object at 0x02742810>
By using the __new__ method, an instance of the class is bound to the Class property _inst when it is created. If Cls._inst is none, the description class is not instantiated, instantiates, and binds the instance to Cls._inst, returning the instance that was created the first time each time it is instantiated. Note When deriving subclasses from Singleton, do not overload new.
Python single-instance mode