Python singleton pattern example details

  • 2020-05-26 09:33:47
  • OfStack

This article illustrates the Python singleton pattern as an example. I will share it with you for your reference as follows:

Singleton pattern: only one instance of a class is guaranteed, and one global access point is provided to access it.

The way to implement a class with only one instance:

1. Having a global variable that allows an object to be accessed does not prevent multiple objects from being externally instantiated.

2, let the class itself save its only instance, this class can guarantee that no other instance can be created.

Singleton pattern for multithreading: lock - double lock

Hungry singleton class: instantiates (statically initializes) itself when the class is loaded. Its advantage is to avoid the security problem of multithreaded access, the disadvantage is to occupy system resources in advance.

Lazy singleton class: instantiates itself the first time it is referenced. Avoid using system resources initially, but have multithreaded access security issues.

Example:


#encoding=utf-8
# The singleton pattern 
def PrintInfo(info):
#  print unicode(info,'utf-8').decode('gbk')
  print info.decode('utf-8').encode('utf-8')
import threading
# Singleton class 
class Singleton():
  instance=None
  mutex=threading.Lock()
  def _init__(self):
    pass
  @staticmethod
  def GetInstance():
    if(Singleton.instance==None):
      Singleton.mutex.acquire()
      if(Singleton.instance==None):
        PrintInfo(' Initialization instance ')
        Singleton.instance=Singleton()
      else:
        PrintInfo(' The singleton has been instantiated ')
      Singleton.mutex.release()
    else:
      PrintInfo(' The singleton has been instantiated ')
    return Singleton.instance
def clientUI():
  Singleton.GetInstance()
  Singleton.GetInstance()
  Singleton.GetInstance()
  return
if __name__=='__main__':
  clientUI();

Results:


 Initialization instance   The singleton has been instantiated   The singleton has been instantiated 

When classmethod is mentioned in Python, staticmethod is mentioned, not because the two have anything to do with each other, but so that users can distinguish between them so that they can write their code more clearly. In C++, we know that functions accessed directly by the class name are called static functions of the class, that is, functions modified by static. It can be seen that classmethod and staticmethod are a concept in C++. So what's the difference between the 2 in python? Let's first look at how a 2 can be declared in python code


class MyClass:
 ...
 @classmethod # classmethod The modifier 
 def class_method(cls, arg1, arg2, ...):
  ...
 @staticmethod # staticmethod The modifier 
 def static_method(arg1, arg2, ...):
  ...

For the classmethod parameter, you need to pass the class name implicitly, while for the staticmethod parameter you don't need to pass the class name, which is the biggest difference between the two.

Both can be called by class name or class instance object. Since classmethod and staticmethod are emphasized, it is better to use class name when writing code. Good programming habits.

For staticmethod, which is set to be defined in a class, 1 is rarely used, and can be replaced with a mode-level (module-level) function. Since we want to define it in a class, it must be the author's consideration.

For classmethod, you can redefine it by subclassing.

Class - level functions are mentioned, along with class - level variables


class MyClass:
 i = 123 # class-level variable
 def __init__(self):
 self.i = 456 # object-level variable
 ...

In order to clearly distinguish the above two i, the best way is to consider that the first cut of python is object, so i=123 belongs to class object, and i=456 belongs to class instance object

For more information about Python, please check out the topics on this site: Python data structure and algorithm tutorial, Python Socket programming skills summary, Python function skills summary, Python string manipulation skills summary, Python introduction and advanced classic tutorial and Python file and directory manipulation skills summary.

I hope this article is helpful to you Python programming.


Related articles: