Method One: adorners
With the "adorner will only perform once" feature
1 defSingleton (CLS):2instances = []#Why is this not direct to none, because the intrinsic function cannot access the non-container variables of the external function3 defgetinstance (*args, * *Kwargs):4 if notinstances:5Instances.append (CLS (*args, * *Kwargs))6 returnInstances[0]7 returngetinstance8 9 @singletonTen classFoo: OneA = 1 A -F1 =Foo () -F2 =Foo () the PrintID (F1), ID (F2)
Method Two: base class
Use "class variable to be unique to all objects", i.e. cls._instance
1 classSingleton (object):2 def __new__(CLS, *args, * *Kwargs):3 if notHasattr (CLS,'_instance'):4Cls._instance = object.__new__(CLS, *args, * *Kwargs)5 returncls._instance6 7 classFoo (Singleton):8A = 1
Method Three: Metaclass
Use "class variable to be unique to all objects", i.e. cls._instance
1 classSingleton (type):2 def __call__(CLS, *args, * *Kwargs):3 if notHasattr (CLS,'_instance'):4Cls._instance = Super (Singleton, CLS).__call__(*args, * *Kwargs)5 returncls._instance6 7 classFoo ():8 __metaclass__= Singleton
Method Four: Borg mode
Use "class variable to be unique to all objects", i.e. __share_state
1 class Foo: 2 __share_state = {}3 def__init__(self):4 Self . __dict__ = self. __share_state
Method Five: Using Import
Use "module will only be import once"
1 # in the file Mysingleton 2 class Foo (object): 3 Pass 4 5 f = Foo ()
Then in other modules, from Mysingleton import F
Take F directly as a singleton object to use
Transferred from: http://blog.csdn.net/handsomekang/article/details/46672047
Elegant Python-Singleton mode strum