Standalone mode and python implementation method, standalone python implementation

Source: Internet
Author: User

Standalone mode and python implementation method, standalone python implementation
Singleton Mode

Singleton Pattern)Is a commonly used software design model, the main purpose of this model is to ensureA class only has one instance.. If you want to create only one instance for a class in the system, the single-instance object can be used.

For example, the configuration information of a server program is stored in a file, and the client reads the configuration file information through an AppConfig class. If the content of the configuration file needs to be used in many places during the program running, that is, the AppConfig object instance needs to be created in many places, this results in multiple AppConfig instance objects in the system, which seriously wastes memory resources, especially when the configuration file contains a lot of content. In fact, for classes like AppConfig, we hope that only one instance object exists during the program running.


Python Implementation of Singleton mode using modules

The Python module is the natural Singleton mode.Because the module will generate.pycFile. When the second import is performed, the file is directly loaded..pycFile, instead of executing the module code again. Therefore, we only need to define the relevant functions and data in a module to obtain a singleton object.

Mysingleton. py

class Singleton:    def foo(self):        print('foo')singleton=Singleton()


Other files

from mysingleton import



Decorator implementation
def singleton(cls):    _instance = {}    def wraper(*args, **kargs):        if cls not in _instance:            _instance[cls] = cls(*args, **kargs)        return _instance[cls]    return wraper@singletonclass A(object):    def __init__(self, x=0):        self.x = xa1 = A(2)a2 = A(3)

Finally, the instance generates an object and stores it in _ instance. The value of _ instance must be

Implementation Based on the _ new _ Method

When we instantiate an object, yesFirst, the _ new _ method of the class is executed.(When we do not write data, object. _ new _ is called by default __),Instantiate object; ThenExecute the _ init _ method of the class.To initialize this object. All of us can implement the singleton mode based on this.

class Singleton():    def __new__(cls, *args, **kwargs):        if not hasattr(cls,'_instance'):            cls._instance=object.__new__(cls)        return cls._instanceclass A(Singleton):    def __init__(self,x):        self.x=xa=A('han')b=A('tao')print(a.x)print(b.x)


To ensure thread security, you need to add a lock internally.

import threadingclass Singleton():    lock=threading.Lock    def __new__(cls, *args, **kwargs):        if not hasattr(cls,'_instance'):            with cls.lock:                if not hasattr(cls, '_instance'):                    cls._instance=object.__new__(cls)        return cls._instanceclass A(Singleton):    def __init__(self,x):        self.x=xa=A('han')b=A('tao')print(a.x)print(b.x)
Two important notes: 1. Except for the module list, the essence of other modes is to set intermediate variables to determine whether the class has been instance. There is a thread security problem in the access and modification of intermediate variables: When the multi-threaded mode is enabled, locks are required. 2. The _ new _ method cannot avoid triggering _ init _ (). The initial member variables will be overwritten. No other methods.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.