Python single-instance mode

Source: Internet
Author: User

The so-called Singleton refers to an instance of a class that can only be created once from beginning to end.

Method 1

Using the __new__ method is simple if you want a class to have at most one instance from start to finish. In Python, classes are created using __new__ to create an instance:

Class Singleton (object):    def __new__ (Cls,*args,**kwargs):        If not hasattr (CLS, ' _inst '):            cls._inst=super (SINGLETON,CLS). __new__ (Cls,*args,**kwargs)        return cls._instif __name__== ' __main__ ':    class A (Singleton):        def __init__ (self,s):            self.s=s          a=a (' Apple ')       b=a (' banana ')    Print ID (a), A.S    print ID (b), B.s

Results:

29922256 banana29922256 Banana

By using the __new__ method, an instance of the class is bound to the Class property _inst when it is created. If Cls._inst is none, the description class is not instantiated, instantiates, and binds the instance to Cls._inst, returning the instance that was created the first time each time it is instantiated. Note When deriving subclasses from Singleton, do not overload __new__.

Method 2:

Sometimes we don't care about whether the generated instance has the same ID, but only its state and behavior. We can allow many instances to be created, but all instances share state and behavior:

Class Borg (object):    _shared_state={}    def __new__ (Cls,*args,**kwargs):        obj=super (BORG,CLS). __new__ ( Cls,*args,**kwargs)        obj.__dict__=cls._shared_state        return obj

Point the __dict__ of all instances to the same dictionary so that the instances share the same methods and properties. The setting of the Name property of any instance, whether modified in __init__ or modified directly, will be affected by all instances. However, the ID of the instance is different. To ensure that class instances can share properties, but not shared with subclasses, be careful to use cls._shared_state instead of borg._shared_state.

Because instances are different IDs, each instance can be a key to the dictionary:

If __name__== ' __main__ ':    class Example (Borg):        pass    a=example ()    b=example ()    c=example ()    adict={}    j=0 for    i in A,b,c:        adict[i]=j        j+=1 for i in    a,b,c:        print Adict[i]

Results:

012

If this behavior is not what you want, you can add the __eq__ and __hash__ methods to the Borg class to bring it closer to the behavior of the singleton pattern:

Class Borg (object):    _shared_state={}    def __new__ (Cls,*args,**kwargs):        obj=super (BORG,CLS). __new__ ( Cls,*args,**kwargs)        obj.__dict__=cls._shared_state        return obj    def __hash__ (self):        return 1    def __eq__ (self,other):        try:            return self.__dict__ is other.__dict__        except:            return Falseif __name_ _== ' __main__ ':    class Example (Borg):        pass    a=example ()    b=example ()    c=example ()    adict={}    j=0 for    i in A,b,c:        adict[i]=j        j+=1 for i in    a,b,c:        print Adict[i]

Results:

222

All instances can be used as a key.

Method 3

When you write a class, a mechanism uses a class name, a base class tuple, a class dictionary to create a class object. This mechanism defaults to type in the new class, and the mechanism is programmable, called the meta-class __metaclass__.

Class Singleton (Type):    def __init__ (self,name,bases,class_dict):        super (Singleton,self). __init__ (Name, bases,class_dict)        self._instance=none    def __call__ (Self,*args,**kwargs):        if Self._instance is None:            Self._instance=super (singleton,self). __call__ (*args,**kwargs)        return self._instanceif __name__== ' __main __ ':    class A (object):        __metaclass__=singleton           a=a ()    b=a ()    print ID (A), id (b)

Results:

34248016 34248016

The ID is the same.

In this example we construct a singleton meta-class and use the __call__ method to simulate the behavior of the function. When you construct Class A, its meta-class is set to Singleton, and when you create class object A, the behavior occurs as follows:

A=singleton (Name,bases,class_dict), A is actually an instance of the Singleton class.

When you create an instance of a, a () =singleton (name,bases,class_dict) () =singleton (name,bases,class_dict). __call__ (), which points all instances of a to the properties of a On instance, this method is actually the same as Method 1.

Method 4

module modules in Python are only loaded once in the program, which is itself a singleton. You can write a module directly, and write the methods and properties you need in a module as a global variable of function and module scope, without having to write classes at all.

There are also methods for synthesizing the advantages of modules and classes:

Class _singleton (object):    class Consterror (TypeError):        pass    def __setattr__ (self,name,value):        if Name in self.__dict__:            raise self. Consterror        self.__dict__[name]=value    def __delattr__ (self,name):        If name in self.__dict__:            raise Self. Consterror        raise Nameerrorimport Syssys.modules[__name__]=_singleton ()

Python does not check the sys.modules to make sure that they are module objects, and we use this to bind the module to a class object, and we will bind the same object later.

To store the code in single.py:

>>> import single>>> single.a=1>>> single.a=2consterror>>> del Single.aconsterror

Method 5

The simplest method:

Class Singleton (object):    Passsingleton=singleton ()

Bind the name Singleton to the instance, and Singleton is the only object of its own class.

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.