Several common implementation methods of Python single mode are described in detail.
This article describes several common implementation methods of Python single mode. We will share this with you for your reference. The details are as follows:
Here python Implementation of the Single Mode, refer to: https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852#1363852
1. Modify __dict__
class Borg: _shared_state = {} def __init__(self): self.__dict__ = self._shared_stateclass Singleton(Borg): def __init__(self, name): super().__init__() self.name = name def __str__(self): return self.namex = Singleton('sausage')print(x)y = Singleton('eggs')print(y)z = Singleton('spam')print(z)print(x)print(y)
Note that this method is not actually implemented in the standalone mode !!
The following methods implement the true standalone mode:
Ii. use metadata
Let's take a look at the metadata description here:
Meta-classes are generally used to create classes.
When executing the class definition, the interpreter must know the correct metadata of the class. The interpreter first looks for class attributes.__metaclass__
If this attribute exists, assign this attribute to this class as its metadata. If this attribute is not defined, it looks up__metaclass__
. If no__metaclass__
Attribute. The Interpreter checks that the name is__metaclass__
If it exists, it is used as a metaclass. Otherwise, use the built-in type as the Meta class of this class.
1. inherit type, use__call__
Note:__call__
Parameters
class Singleton(type): _instance = None def __call__(self, *args, **kw): if self._instance is None: self._instance = super().__call__(*args, **kw) return self._instanceclass MyClass(object): __metaclass__ = Singletonprint(MyClass())print(MyClass())
2. inherit type, use__new__
Note:__new__
Parameters
class Singleton(type): _instance = None def __new__(cls, name, bases, dct): if cls._instance is None: cls._instance = super().__new__(cls, name, bases, dct) return cls._instanceclass MyClass(object): __metaclass__ = Singletonprint(MyClass())print(MyClass())
3. Inheritanceobject
, Use__new__
Note:__new__
Parameters
class Singleton(object): _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instanceclass MyClass(object): __metaclass__ = Singletonprint(MyClass())print(MyClass())
There is also a clever way to implement the standalone mode.
Usageclassmethod
class Singleton: _instance = None @classmethod def create(cls): if cls._instance is None: cls._instance = cls() return cls._instance def __init__(self): self.x = 5 # or whatever you want to dosing = Singleton.create()print(sing.x) # 5sec = Singleton.create()print(sec.x) # 5