Python3 Implementing a singleton pattern

Source: Internet
Author: User

A singleton pattern is a design pattern that ensures that a class has only one instance in the entire system
Benefits of using Singleton mode:
1, each instance will occupy a certain amount of memory resources, and the initialization of the instance will affect the performance, so when the entire system needs only one instance, the use of Singleton mode not only reduces the resource consumption, but also because it is initialized only once and can speed up the performance of the operation. For example, when a program reads configuration information through a class, and the program needs to use configuration information in multiple places, the entire program runs with only one instance object, which reduces memory resources and ensures that the program obtains the same configuration information in multiple locations.
2, the use of single-case mode can be synchronized control, counter synchronization, the program to read the configuration information in these scenarios if there is only one instance, you can guarantee consistency.

In Python, you can typically implement a singleton pattern in 4 ways:

1, through the module call
2. Using the __new__ method
3, the use of decorative device
4. Using meta-class (Metaclass)

One, through the module call

Practice: Write the class that needs to implement the singleton in the module file, and then introduce the module through import to get a singleton object.
Principle: In Python3, when the module file is first imported, the PYc file is generated in the __PYCACHE__ directory under the program directory, and the PYc file is loaded directly after the import. Thus, a single case is achieved.

Implementation code:

    • module_demo.py
      class singleton_cal:def foo(self):     passexport_singleton = singleton_cal()
    • use_module.py
      from module_demo import export_singletona = export_singletonfrom module_demo import export_singletonb = export_singletonprint(a == b)print(id(a) == id(b))


      Can be found, multiple call/import modules, using the same instance object

Second, the use of __new__ method

_new__ and _init__ the difference:
__new\
: constructor method Called when creating an instance object
_Init_: Initialization method for setting the related properties of an instance
When Python creates an instance, it calls the __new__ construction method and then initializes the instance using __init__.
We can use __new__ to influence the creation of an instance, thus implementing a singleton.

Implementation code:

    • use_new.py
class Singleton(object):    __instance = None    def __new__(cls,*args,**kwargs):        if not cls. __instance:            cls.__instance = super().__new__(cls,*args,**kwargs)        return cls.__instancea = Singleton()b = Singleton()print(a == b)print(id(a) == id(b))


In the above code, a private class variable __instance is declared, when __instance is not none, represents an existing instance of the system, returns the instance directly, and if the __instance is None, indicates that there is no such instance in the system, creates a new instance and returns.

Third, the use of decorative device
    • use_decorator.py
from functools import wrapsdef singleton(cls):    instances = {}    @wraps(cls)    def getinstance(*args, **kwargs):        if cls not in instances:            instances[cls] = cls(*args, **kwargs)        return instances[cls]    return getinstance@singletonclass singleCls(object):def foo(self):    passa = singleCls()b = singleCls()print(a == b)print(id(a) == id(b))


Only when the SINGLECLS is first called, the adorner executes from instances={}, and then when the singlecls is called, only the getinstance function is executed, which is the adorner's feature, and with this feature, when we call singlecls multiple times, In the GetInstance function, the class is judged to exist in the instances dictionary, if it does not exist, the class instance is created and added to the instances dictionary, and an instance of the class in the dictionary is returned, and if present, the instance of the class in the dictionary is returned directly. You can use this adorner to implement a singleton for multiple classes.

Iv. use of meta-classes (Metaclass)

The meta-class creates all type objects, including object objects, and the system default meta-class is type.

The relationships of instances, classes, parent classes, and meta-classes can be expressed as

The __call method in the meta-class is called when an instance of the class has been created for a class that is a meta class, for example: Class A takes Class B as a meta class, and when a creates an instance, \ Call in Bis called. Use \call__ to achieve control of instance creation.

Implementation code:

    • use_metaclass.py
class SingletonMeta(type):    __instance = None    def __call__(cls,*args,**kwargs):        if not cls.__instance:            cls.__instance = type.__call__(cls,*args,**kwargs)        return cls.__instanceclass myclass(metaclass = SingletonMeta):    def foo(self):        passa = myclass()b = myclass()print(a==b)print(id(a)==id(b))


When you customize a meta class, you typically inherit from type, declare a private class variable __instance Save the class instance, and when __instance is None, call the __call__ method of type to create an instance of the class, save to __instance and return; Instance is not none, the __instance is returned directly and the instance is not recreated.
Welcome to scan the code to pay attention to the public "Keepcode", share more technical good text, and provide technical e-book free download, a little progress every day ~ ~ ~

Python3 Implementing a singleton pattern

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: info-contact@alibabacloud.com 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.