Method One
Implement the __new__ method, and then bind an instance of the class to the class variable _instance, or if cls._instance is None, the class has not been instantiated, new is an instance of the class, and returns, if Cls._instance is not none, Return directly to _instance, the code is as follows
classSingleton (object):def __new__(CLS, *args, * *Kwargs):if notHasattr (CLS,'_instance'): Orig=Super (Singleton, CLS) cls._instance= orig.__new__(CLS, *args, * *Kwargs)returncls._instanceclassMyClass (Singleton): a= 1 One=MyClass ()=MyClass ()#One and both are identical and can be detected with ID (), = =, isPrintID (one)#29097904PrintID (both)#29097904Printone = =#TruePrintOne isBoth#True
Method Two
is essentially an upgraded version of method one, using the advanced Python usage of __metaclass__ (meta Class), with the following specific code:
classSingleton2 (type):def __init__(CLS, name, bases, Dict): Super (Singleton2, CLS).__init__(name, bases, dict) cls._instance=Nonedef __call__(CLS, *args, * *Kwargs):ifCls._instance isnone:cls._instance= Super (Singleton2, CLS).__call__(*args, * *Kwargs)returncls._instanceclassMyClass2 (object):__metaclass__=Singleton2 a= 1 One=MyClass2 ()=MyClass2 ()PrintID (one)#31495472PrintID (both)#31495472Printone = =#TruePrintOne isBoth#True
Method Three
Using the Python Adorner (decorator) to implement a singleton pattern is a more pythonic approach; The code for the simple interest class itself is not a singleton, and the pass decorator makes it a singleton, with the following code:
defSingleton (CLS, *args, * *Kwargs): Instances= {} def_singleton ():ifCls not inchInstances:instances[cls]= CLS (*args, * *Kwargs)returnInstances[cls]return_singleton @singletonclassMyClass3 (object): a= 1 One=MYCLASS3 ()=MYCLASS3 ()PrintID (one)#29660784PrintID (both)#29660784Printone = =#TruePrintOne isBoth#True
Python Single case