In Python, the singleton mode is a commonly used software design pattern. The main purpose of this mode is to ensure that a certain class can only have one instance object in memory; it is created through the singleton mode method. A class has only one instance object in the current process. The singleton pattern is divided into: 1. Lazy style, creating objects as soon as the class is loaded; 2. Hungry style, creating objects only when used.
Singleton Pattern is a commonly used software design pattern. The main purpose of this pattern is to ensure that only one instance of a certain class exists. Singleton objects come in handy when you want only one instance of a certain class to appear in the entire system.
For example, the configuration information of a server program is stored in a file, and the client reads the configuration file information through an AppConfig class. If the contents of the configuration file need to be used in many places during the running of the program, that is to say, instances of the AppConfig object need to be created in many places, which will lead to the existence of multiple AppConfig instance objects in the system, and this will seriously waste memory. resources, especially if the configuration file contains a lot of content. In fact, for a class like AppConfig, we hope that only one instance object exists while the program is running.
There are three main points of the singleton mode: First, a class can only have one instance; second, it must create this instance by itself; third, it must provide this to the entire system by itself. Example.
In Python, we can use a variety of methods to implement the singleton pattern:
Use modules
Use __new__
Using decorator
Using module
In fact, Python’s module is a natural singleton mode.
Because the module will generate a .pyc file when it is imported for the first time. When it is imported for the second time, the .pyc file will be loaded directly without executing the module code again. Therefore, we only need to define the relevant functions and data in a module to get a singleton object.
If we really want a singleton class, consider doing this:
#tests1.py class MyClass(object): def foo(self): print('MyClass.foo') my_class_obj=MyClass()
Save the above code in the file tests1.py, and then use it like this:
from .tests1 import my_class_obj my_class_obj.foo()
Use __new__
In order to make only one instance of the class appear, we can use __new__ to control the creation process of the instance. The code is as follows:
class MyClass(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(MyClass, cls).__new__(cls, *args, **kwargs) return cls._instance class HerClass(MyClass): a = 1
In the above code, we associate the instance of the class with a class variable _instance. If cls._instance is None, create an instance, otherwise return cls._instance directly.
The execution is as follows:
one = HerClass() two = HerClass() print(one == two) #True print(one is two) #True print(id(one), id(two)) #42818864 42818864
Using the decorator
We know that the decorator can be modified dynamically The functionality of a class or function. Here, we can also use a decorator to decorate a class so that it can only generate one instance. The code is as follows:
from functools import wraps def singleton(cls): instances = {} @wraps(cls) def getinstance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return getinstance @singleton class MyClass(object): a = 1
Above, we defined a decorator singleton, which returns an internal function getinstance , this function will determine whether a certain class is in the dictionary instances. If it does not exist, cls will be used as the key and cls(*args, **kw) will be stored as the value in instances. Otherwise, instances[cls] will be returned directly.
The above is the detailed content of What is python singleton pattern. For more information, please follow other related articles on the PHP Chinese website!