1 use
__new__Method
Class Singleton (object):
Def __new__ (CLS, *args, **kw):
If not hasattr (CLS, ' _instance '):
Orig = Super (Singleton, CLS)
Cls._instance = orig.__new__ (CLS, *args, **KW)
Return cls._instance
Class MyClass (Singleton):
A = 1
2 Shared properties
When you create an instance, you point all instances to the __dict__ same dictionary, so that they have the same properties and methods.
class Borg(object): _state = {} def __new__ (cls,< Span class= "crayon-h" > *args, **kw) Span class= "Crayon-o" >: ob = super (borg, cls) . __new__ (cls, Span class= "Crayon-o" >*args, **kw) ob. __dict__ = cls. _state return ob class MyClass2(Borg): a = 1 3 Adorner version
Def Singleton (CLS, *args, **kw):
instances = {}
Def getinstance ():
If CLS not in instances:
INSTANCES[CLS] = CLS (*args, **KW)
return INSTANCES[CLS]
Return getinstance
@singleton
Class MyClass:
...
4:import version
As a Python module, it's a natural, single-case pattern.
# mysingleton.py
Class My_singleton (object):
def foo (self):
Pass
My_singleton = My_singleton ()
# to use
From Mysingleton import My_singleton
My_singleton.foo ()
The application of a singleton pattern in Python