Use the __new__ method to implement a singleton pattern:
classSingleTon (object):def __new__(CLS, *args, * *kw):if notHasattr (CLS,'instance'): Cls.instance= object.__new__(CLS, *args, * *kw)returncls.instanceclassTestClass (SingleTon):def __init__(self, num): Self.num=Numtest1= TestClass (1) Test2= TestClass (2)PrintTest1.num, Test2.numPrintID (test1), ID (test2)
When the TestClass class is instantiated, its parent class, the __new__ method of Singleton, is called by default because its own __new__ method is not overridden. The __new__ method of Singleton is overridden to return a class instance only if it does not have a instance property on its own, ensuring that only 1 instances are generated.
The results of the above code run:
2 248477016 48477016
Two instances have the same ID, which means the same instance. However, its num value is 2 because the second time the test2 is instantiated, its num is overwritten with 2 in __init__.
Python implementation Singleton mode