Python3.8.1
The singleton mode is to ensure that there is only one instance of a class. When you want the entire system to have only one instance of a certain class, the singleton mode comes in handy
classMyClass(object):
def foo(self):return None
obj1 =MyClass()
obj2 =MyClass()print(obj1 is obj2)print(id(obj1))print(id(obj2))
classMyClass(object):
def foo(self):return None
obj =MyClass()
use:
from singleton.mysingleton import obj
The python module is a natural singleton mode, because when the module is imported for the first time, it will generate a .pyc file. When it is imported for the second time, it will directly load the .pyc file instead of executing the module code again. We define related functions and data in a module, and we can get a singleton object
def singleton(cls):"""Decorator function"""
class_instance ={} #Define a class that accepts instances
def singleton_inner(*args,**kwargs):if cls not in class_instance: #Determine whether the class has been instantiated
class_instance[cls]=cls(*args,**kwargs) #Not instantiated->Instantiate->Add the instantiated object to the dictionary
return class_instance[cls] #Return instantiated object
return singleton_inner
@ singleton
classMyClass(object):
def foo(self):return None
obj1 =MyClass()
obj2 =MyClass()print(obj1 is obj2)print(id(obj1))print(id(obj2))
Add a decorator before the class. The purpose of the decorator here is only one, that is, before the class is instantiated, first determine whether the class has been instantiated, if not, instantiate it, if it has been instantiated, the test returns the previous Instantiate object
classMyClass(object):
def foo(self):return None
@ classmethod
def get_instance(cls,*args,**kwargs):"""Instantiate function"""if not hasattr(cls,'_instance'):
cls._instance =cls(*args,**kwargs)return cls._instance
obj1 = MyClass.get_instance()
obj2 = MyClass.get_instance()print(obj1 is obj2)print(id(obj1))print(id(obj2))
obj3 =MyClass()print(id(obj3))
There are two disadvantages of implementing a single instance in this way:
classMyClass(object):
def foo(self):return None
def __new__(cls,*args,**kwargs):if not hasattr(cls,'_instance'):
cls._instance =super().__new__(cls)return cls._instance
obj1 =MyClass()
obj2 =MyClass()print(obj1 is obj2)print(id(obj1))print(id(obj2))
**The instantiation process of an object is to first execute the new method of the class. If we do not write, the new method of the object will be called by default to return an instantiated object, and then the init method will be called to initialize the object. , We can implement singleton according to this **