Python3 implements the singleton design pattern

General realization of singleton pattern##

Hungry Chinese##

***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

Python3 implements the singleton design pattern
python3 simply implements the combined design pattern
Python implements the brick-and-mortar game
How Python implements the mail function
Python simply implements the snake game
Python implements the steepest descent method
Python implements the actual banking system
How Python implements the timer function
Python implements the aircraft war project
Python implements the sum of fractional sequences
python implements the gradient method python the fastest descent method
Python design patterns
2.1 The Python Interpreter (python interpreter)
Python implements the shuffling of the cards in Doudizhu
Python implements the source code of the snake game
Python implements tic-tac-toe game
Python implements tic-tac-toe game
Python implements man-machine gobang
Python implements Tetris game
Python implements image stitching
Python implements minesweeper game
Python implements scanning tools
Consolidate the Python foundation (2)
Python implements threshold regression
Python implements minesweeper games
Python implements electronic dictionary
Python implements guessing game
Consolidate the foundation of Python (4)
Python implements simple tank battle
Consolidate the foundation of Python(7)
Python implements udp chat window
Python implements WeChat airplane game
Python implements word guessing game
Consolidate the foundation of Python(6)
Ubuntu install the latest Python 3.
Python implements parking management system
Python implements digital bomb game
Python implements TCP file transfer
Python realizes the guessing game
The difference between Python extensions
Python numpy implements rolling case
OpenCV Python implements puzzle games
Python implements simple tic-tac-toe game
Consolidate the foundation of Python(5)
Python implements password strength verification
Python implements car management system
Python implements code block folding
Python implements panoramic image stitching
Python implements SMTP mail sending
Python implements multi-dimensional array sorting
How Python implements FTP function
Python implements mean-shift clustering algorithm
Python implements verification code recognition
Python implements gradient descent method
Python implements text version minesweeper
Consolidate the foundation of Python (3)
Python implements image stitching function