There is a scenario where we encapsulate the data into a class or a method of a class, but we're new out of this class just to get this part of the data, so when it's called multiple times, it's a waste of memory to take the data and put it in memory every time.
Then we can think, we get the data once, put it into memory, next time to use the same time to make a judgment, if there is in memory, then no need to take.
This is the time to design a "single-instance mode".
Method 1:
classFoo (object):__instance=Nonedef __new__(CLS, *args, * *Kwargs):"""Singleton mode:p Aram CLS::p Aram args::p Aram Kwargs:: Return:""" #Notice the judgment here, when Cls.__instance is None, go to the real new, otherwise return directly. if notCls.__instance: obj= object.__new__(CLS, *args, * *Kwargs) cls.__instance=objreturnCls.__instance
Object = Foo () # call __new__ First, and then call __init__,__init__ similar to the constructor.
It is also necessary to add that the Python creation class instance, in fact, like Java, is called New, but Python is the new method is written in the built-in (__new__), we can also know that when writing object = Foo (), the first tune __new__ , the __init__ of the re-tune.
Method Two:
classFoo (object): Instance=Nonedef __init__(self): Self.name='haha'
# In fact and method one of the truth, suggested using method one. @classmethoddefget_instance (CLS):iffoo.instance:returnfoo.instanceElse: Foo.instance=Foo ()returnfoo.instancedefprocess (self):return '123'
Python implementation Singleton mode