***The lazy man style is to achieve a singleton through a method, I don't use it very often, so I will write a hungry man style here. I'll make up the lazy man style later. ***
The core function of the singleton pattern is to ensure that a class has only one object of that type. To avoid excessive memory consumption when an object is called too much, you can use singleton mode.
Creating an object in python will call the __new__
method to allocate its memory space for the created object, and return a reference to the object, which will then be passed to the __init__
function for instantiation.
In general, there is no need to call the new method. This step is necessary when using a singleton. When rewriting the new method, the class cls of the current instance needs to be returned: return super().__new__(cls)
. After getting the allocated memory space reference, start to instantiate the object. The code can be simply written as follows:
classClassObj(object):
def __new__(cls):print("To allocate memory")returnsuper().__new__(cls)
def __init__(self):print("Start initialization")
cobj =ClassObj()
The results are as follows:
But the above code does not implement the singleton mode. At this time, we need to change the above code.
When using the new method, determine whether it has been instantiated:
classClassObj(object):
instance=None
def __new__(cls):if cls.instance is None:
cls.instance=super().__new__(cls)print("To allocate memory")else:print("Already assigned")return cls.instance
def __init__(self):print("Already assigned")
cobj =ClassObj()
cobj1 =ClassObj()
The above code defines a member variable instance in ClassObj, which is used to store the allocated space reference, and finally returns instance in the new method; assuming that this type of object is created for the first time and instance is None, it will be instantiated. If it is not None, it will prompt that it has been allocated and will not allocate space again for creation. The results are as follows:
The above results only allocate space when the object is created for the first time, and no space is created for the objects created afterwards.
At this time, you can also directly output the class object to view the space:
cobj =ClassObj()
cobj1 =ClassObj()print(cobj)print(cobj1)
The result is the same as follows:
Recommended Posts