Python Singleton Mode)

Source: Internet
Author: User

Singleton mode: ensures that a class has only one instance and provides a global access point to access it.

 

There is only one way to implement a class:

1. Make a global variable so that an object is accessed, but it cannot prevent external instantiation of multiple objects.

2. Let the class itself save its unique instance. This class can ensure that no other instance can be created.

Singleton mode for multithreading: Lock-double lock

ELE. Me Singleton class: instantiate itself when the class is loaded (static initialization ). Its advantage is that it avoids the security problem of multi-thread access, and its disadvantage is that it occupies system resources in advance.

lazy Singleton class: instantiate itself when it is referenced for the first time. Avoid occupying system resources at the beginning, but there are multi-threaded access security issues.

Instance:

 

#  Encoding = UTF-8  #  Singleton Mode  Def  Printinfo (Info ):  #  Print Unicode (Info, 'utf-8'). Decode ('gbk ')      Print Info. Decode ( '  UTF-8  ' ). Encode ( '  UTF-8  '  ) Import  Threading  #  Singleton type  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 an 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 (); 

 

result:

the initialized instance Singleton has been instantiated and The Singleton has been instantiated.

append description @ staticmethod in Python, classmethod refers to staticmethod, not because of its relationship, In order to differentiate users so that they can write Code more clearly. In C ++, we understand that a function directly accessed by class name is called a static function of the class, that is, a static modified function. In C ++, classmethod and staticmethod are concepts. So what is the difference between the two in Python? Let's take a look at how the two are declared in Python code.

  class   myclass :... @ classmethod  #  classmethod modifier   def   class_method (CLS, arg1, arg2 ,...) :... @ staticmethod  #  staticmethod modifier   def   static_method (arg1, arg2 ,...) :...  

For the classmethod parameter, the class name needs to be passed implicitly, while the staticmethod parameter does not need to pass the class name. In fact, this is the biggest difference between the two.
Both can be called through the class name or class instance object, because the emphasis is on classmethod and staticmethod, so it is best to use the class name when writing code, good programming habits.
Staticmethod is set to be defined in the class. It is rarely used in this way. It can be replaced by a module-level function. Since we want to define it in a class, the author must consider it.
For classmethod, you can use subclasses to redefine it.
When it comes to class-level functions, it also mentions class-level variables.

 

 
ClassMyclass: I= 123#Class-level variableDef _ 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 an object, so I = 123 belongs to class object, and I = 456 belongs to class instance object.

 

 

Related Article

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.