Home  >  Article  >  Backend Development  >  How to implement singleton in python

How to implement singleton in python

(*-*)浩
(*-*)浩Original
2019-06-27 09:28:513399browse

Singleton Pattern is a commonly used software design pattern. The main purpose of this pattern is to ensure that only one instance of a certain class exists. Singleton objects come in handy when you want only one instance of a certain class to appear in the entire system.

How to implement singleton in python

In Python, we can use a variety of methods to implement the singleton pattern (recommended learning: Python video tutorial)

In fact, Python’s module is a natural singleton mode, because when the module is imported for the first time, a .pyc file will be generated. When it is imported for the second time, the .pyc file will be loaded directly instead of The module code will be executed again. Therefore, we only need to define the relevant functions and data in a module to get a singleton object.

Use decorators

def Singleton(cls):
    _instance = {}
    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
        return _instance[cls]

    return _singleton
@Singleton
class A(object):
    a = 1

    def __init__(self, x=0):
        self.x = x
a1 = A(2)
a2 = A(3)

Use classes, When we implement a singleton, in order to ensure thread safety we need to Internal lock addition

We know that when we instantiate an object, we first execute the __new__ method of the class (when we do not write it, object.__new__ is called by default) to instantiate the object; Then execute the __init__ method of the class to initialize the object. Based on this, we can implement the singleton mode

Use __metaclass__ (metaclass)

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to implement singleton in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn