Python single-instance mode

Source: Internet
Author: User

Python's singleton pattern implements the __new__ method of the:     rewrite class to      refer to the explanation of the official website:         3.4.1. Basic customization                 object.__new__ (cls[,  ...])                 called to  create a new instance of class cls. __new__ ()  is a  static method  (special-cased so you need not declare it as  Such)  that takes the class of which an instance was  requested as its first argument. the remaining arguments are  those passed to the object constructor expression  (the call to  the class).  the return value of&Nbsp;__new__ ()  should be the new object instance  (usually an  INSTANCE&NBSP;OF&NBSP;CLS) .                 typical implementations create a new instance of the  class by invoking the superclass ' s __new__ ()  method using super ( CURRENTCLASS,&NBSP;CLS). __new__ (cls[,  ...])  with appropriate arguments and then modifying the newly-created  instance as necessary before returning it.                 if __new__ ()  returns an instance  of cls, then the new instance ' s __init__ ()  method will be  invoked like __init__ (self[,...]),  where self is the new instance and the remaining arguments are the same as  were passed to __new__ () .                 if __new__ ()  does not return an instance of  cls, then the new instance ' s __init__ ()  method will not be  invoked.                 __new__ ()  is intended mainly to allow subclasses of immutable  types  (like int, str, or tuple)  to customize instance creation.  It is also commonly overridden in custom metaclasses in  Order to customize class creation.class db (object):     __instance  = none &nbsP;  def __init__ (self):        self.host =  ' 10.0.0.1 '         self.port =  ' 3306 '          self.user =  ' Root '          self.password =  ' 123456 '     def __new__ (Cls,*args,**kwargs):        if cls.__instance is  None:            cls.__instance = super (DB,CLS). __new__ (Cls,*args,**kwargs)         return cls.__instance               in [2]: a=db () in [3]: b=db () In [4]: c=db () in  [5]: aOut[5]: <__main__.db at 0x1066fd390>In [6]: bOut[6]: < __main__.db at 0x1066fd390>in [7]: cout[7]: <__main__.db at 0x1066fd390>in [8]:  a.hostout[8]:  ' 10.0.0.1 ' in [9]: b.portout[9]:  ' 3306 ' in [10]: c.userout[10]:   ' root ' in [11]: c.password= ' uiso ' in [12]: b.passwordout[12]:  ' Uiso ' In [13]:  a.passwordOut[13]:  ' Uiso '

As you can see, initialization & instantiation uses the same object, which is very good to keep long connections. But this notation is not thread-safe.


In multi-threading, we need to import the features using threading, using locks to ensure thread safety


Lock = Threading. Lock ()


Rewrite the __new__ method to:

def __new__ (Cls, *args, **kwargs):         if not cls.__instance:             try:                 lock.acquire ()                  if not cls.__instance:                     cls.__instance = super (DB,&NBSP;CLS). __ new__ (Cls, *args, **kwargs)              finally:                 Lock.release ()         return cls.__instance 

Double check to keep the thread safe.

Python single-instance mode

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.