Singleton pattern in Python

黄舟
Release: 2017-02-04 16:38:19
Original
1368 people have browsed it

Singleton Mode

Singleton Mode 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.

For example, the configuration information of a server program is stored in a file, and the client passes an AppConfig Class to read configuration file information. If there are many places where the contents of the configuration file need to be used during the running of the program, that is to say, AppConfig needs to be created in many places. Object instance, which results in the existence of multiple AppConfig instance objects in the system, which will seriously waste memory resources, especially when the configuration file contains a lot of content. In fact, something like AppConfig For such a class, we hope that only one instance object will exist during the running of the program.

In Python, we can use a variety of methods to implement the singleton pattern:

  • Use modules

  • Use_ _new__

  • Use decorator

  • Use metaclass

Use modules

In fact, Python’s module is a natural singleton mode, because when the module is imported for the first time, .pyc will be generated. file, when imported for the second time, .pyc will be loaded directly file without executing the module code again. Therefore, we only need to define the relevant functions and data in a module to get a singleton object. If we really want a singleton class, consider doing this:

# 
mysingleton.py
class My_Singleton(object):
    def foo(self):
        pass
 
my_singleton = My_Singleton()
Copy after login

Save the above code in the file mysingleton.py and use it like this:

from 
mysingleton import my_singleton
 
my_singleton.foo()
Copy after login

Use __new__

In order to make only one instance of the class appear, we can use __new__ to control the instance creation process. The code is as follows:

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kw):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)  
        return cls._instance  
 
class MyClass(Singleton):  
    a = 1
Copy after login

In the above code, we will The instance of the class is associated with a class variable _instance. If cls._instance is None, the instance is created, otherwise it is returned directly. cls._instance.

The execution is as follows:

>>> one = MyClass()
>>> two = MyClass()
>>> one == two
True
>>> one is two
True
>>> id(one), id(two)
(4303862608, 4303862608)
Copy after login

Using decorators

We know that decorators (decorators) can dynamically modify the functions of a class or function . Here, we can also use a decorator to decorate a class so that it can only generate one instance. The code is as follows:

from 
functools import wraps
 
def singleton(cls):
    instances = {}
    @wraps(cls)
    def getinstance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return getinstance
 
@singleton
class MyClass(object):
    a = 1
Copy after login

Above, we defined a decorator singleton, which returns an internal function getinstance , this function will determine whether a certain class is in the dictionary instances , if it does not exist, cls will be used as the key and cls(*args, **kw) will be stored as the value in instances. Otherwise, it will be returned directly. instances[cls].

Using metaclass

Metaclass can control the creation process of a class. It mainly does three things:

  • Creation of interception class

  • Modify the definition of the class

  • Return the modified class

The code to implement singleton mode using metaclass is as follows:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]
 
# 
Python2
class MyClass(object):
    __metaclass__ = Singleton
 
# 
Python3
# 
class MyClass(metaclass=Singleton):
#    pass
Copy after login


Summary

Python’s module is a natural singleton mode. This should be enough in most cases. Of course, we can also use methods such as decorators and metaclasses


The above is the content of the singleton mode in Python , for more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template