How to use python singleton
This article will explain in detail how to use python singletons. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
As a singleton, the object created by the class has only a unique instance in the system.
1. Define a class attribute with an initial value of None, and record the reference of a single object.
2. Override the _ _ new__ method.
3. Call the parent class method to allocate space when the class attribute is is None.
Record the results in the class properties.
4. Returns the object reference of the class property record.
Example
Class MusicPlayer (object): # define class attribute record singleton object reference instance = None def _ _ new__ (cls, * args, * * kwargs): # 1. Determine whether the class attribute has been assigned if cls.instance is None: cls.instance = super (). _ _ new__ (cls) # 2. Return class attributes singleton reference return cls.instance on "how to use python singleton" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.