#-*-encoding=utf-8-*-classSingleton (object):def __new__(CLS, *args, * *kw):if notHasattr (CLS,'_instance'): Orig=Super (Singleton, CLS) cls._instance= orig.__new__(CLS, *args, * *kw)returncls._instanceclassMyClass (Singleton): a= 1 One=MyClass ()=MyClass () two.a= 3PrintOne.a#3#One and both are identical and can be detected with ID (), = =, isPrintID (one)PrintID (both)Printone = = Both#TruePrintOne is Both#TrueclassBorg (object): _state= {} def __new__(CLS, *args, * *kw): OB= Super (Borg, CLS).__new__(CLS, *args, * *kw) ob.__dict__=cls._statereturnobclassMyClass2 (Borg): a= 1 One=MyClass2 ()=MyClass2 () two.a= 3PrintOne.aPrintID (one)PrintID (both)Printone = = BothPrintOne is BothclassSingleton2 (type):def __init__(CLS, name, bases, Dict): Super (Singleton2, CLS).__init__(name, bases, dict) cls._instance=Nonedef __call__(CLS, *args, * *kw):ifCls._instance isnone:cls._instance= Super (Singleton2, CLS).__call__(*args, * *kw)returncls._instanceclassMyClass3 (object):__metaclass__=Singleton2one=MYCLASS3 ()=MyClass3 () two.a= 3PrintOne.a#3PrintID (one)#31495472PrintID (both)#31495472Printone = = Both#TruePrintOne is Both#TruedefSingleton (CLS, *args, * *kw): Instances= {} def_singleton ():ifCls not inchInstances:instances[cls]= CLS (*args, * *kw)returnInstances[cls]return_singleton@singletonclassMyClass4 (object): a= 1def __init__(Self, x=0): self.x=Xone=MyClass4 ()=MyClass4 () two.a= 3PrintOne.a#3PrintID (one)#29660784PrintID (both)#29660784Printone = = Both#TruePrintOne is Both#Trueone.x = 1Printone.x#1Printtwo.x#1
CLASS3 uses a meta-class.
The CLASS4 used the wonderful decorator.
Python single-instance mode