Python Singleton Pattern Example

Source: Internet
Author: User
This example describes the Python singleton pattern. Share to everyone for your reference, as follows:

Single-case mode: Ensure that a class has only one instance and provides a global access point to access him.

A way to implement only one instance of a class:

1, let a global variable make an object accessible, but he cannot prevent the external instantiation of multiple objects.

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

Multi-threaded Singleton mode: locking-double lock

a hungry man Singleton class: instantiates itself (statically initialized) when the class is loaded. The advantage is that it avoids the security problem of multi-threaded access, and the disadvantage is that it occupies the system resources beforehand.

lazy Singleton class: The first time you are referenced, you instantiate yourself. Avoid using system resources at the start, but have multiple thread access security issues.

Instance:

#encoding =utf-8# Single-case mode def printinfo (info): #  Print Unicode (info, ' Utf-8 '). Decode (' GBK ')  print Info.decode (' Utf-8 '). Encode (' utf-8 ') import threading# Singleton 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 (' Initialize instance ')        Singleton.instance=singleton ()      Else:        printinfo (' Singleton already instantiated ')      Singleton.mutex.release ()    Else:      Printinfo (' Singleton already instantiated ')    return singleton.instancedef Clientui ():  singleton.getinstance ()  Singleton.getinstance ()  singleton.getinstance ()  returnif __name__== ' __main__ ':  clientui ();

Results:

Initializes an instance of a singleton that has been instantiated already instantiated

Additional explanations @staticmethod mention of Classmethod in Python refers to Staticmethod, not because of the relationship between the two, but to let the user differentiate to write the code more clearly. In C + +, we understand that functions that are accessed directly through the class name are called static functions of the class, that is, the function of the static modifier, and the Classmethod and Staticmethod in C + + are seen as a concept. So what's the difference between the two in Python? Let's see how they're declared in Python code.

Class MyClass: ... @classmethod # classmethod modifier def class_method (CLS, arg1, Arg2, ...):  ... @staticmethod # STATICME Thod modifier def static_method (arg1, Arg2, ...):  ...

For Classmethod parameters, it is necessary to pass the class name implicitly, while the Staticmethod parameter does not need to pass the class name, in fact, this is the most important difference between them.

Both can be called by the class name or class instance object, because the emphasis is classmethod and staticmethod, so it is best to use the class name when writing code, good programming habits.

For Staticmethod, which is set up to be defined in a class, is rarely used in general, and can be replaced with a module-level (Module-level) function. Since it is to be defined in the class, there must be the author's consideration.

For Classmethod, you can redefine it by subclasses.

refers to class-level functions, incidentally, 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 everything in Python is object, so i=123 belongs to class object, i=456 belongs to class instance object

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.