1. In Python, the singleton pattern is easy to implement, and you can find many answers by flipping through the relevant tutorials on the Web.
such as this:
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 Selfa=hello () B=hello () #************************** result *******************************<__main__.hello Object at 0x7f8afeaf1150><__main__.hello Object @ 0x7f8afeaf1150>process finished with exit code 0
As you can see, the memory address of the two instances is the same, which means that the two are the same instance.
Note: If we rewrite the __new__ function, we need to inherit the object class.
2. It is important to note that the self and cls._instance_one in the above example are actually the same thing, we can simply do a test:
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 Selfa=hello () #************************************** result ******************* <__main__.hello object at 0x7fb31f65e150><__main__.hello object at 0x7fb31f65e150>process Finished with exit code 0
3. If we need to initialize the singleton mode only once, we only need to add a flag:
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>endend
4. Note that the _flag in the above example is written in a class, outside the class, we can also do an experiment:
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._flaga=hello () B=hello () #*************************************result ********* 1010Process finished with exit code 0
You can see that the two are equivalent.
When Python, singleton mode, multi-instance mode, one-time initialization encounters together