Five common methods for creating the Singleton mode in Python

Source: Internet
Author: User
The five common methods for creating the Singleton mode in Python are called Singleton, which means that an instance of a class can only be created once from the beginning.

Method 1

If you want to make a class have only one instance from the beginning, it is easy to use the _ new _ method. In Python, classes use _ new _ to create instances:

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


Result:

29922256 banana

29922256 banana

The _ new _ method is used to bind the class instance to the class property _ inst when it is created. If the value of cls. _ inst is None, the class has not yet been instantiated. the instance is instantiated and bound to cls. _ inst. the instance created for the first instantiation will be returned each time it is instantiated. Do not overload _ new _ when deriving a subclass from Singleton __.

Method 2:

Sometimes we do not care about whether the generated instance has the same id, but only about its status and behavior. We can allow many instances to be created, but all

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 attributes. All instances are affected whether they are modified in _ init _ or directly. However, the instance IDs are different. To ensure that the class instance can share attributes but not the subclass, use cls. _ shared_state instead of Borg. _ shared_state.

Because the instance has different IDs, each instance can be used as a dictionary key:

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]

Result:

0

1

2

If this behavior is not what you want, you can add the _ eq _ and _ hash _ methods for the Borg class so that it is closer to the behavior in the Singleton mode:

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]

Result:

2

2

2

All instances can be used as a key.

Method 3

When you write a class, a mechanism will use the class name, base class tuples, and class dictionary to create a class object. In the new class, this mechanism defaults to type, and this mechanism is programmable, called 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)

Result:

34248016 34248016

The IDs are the same.

In this example, we construct a Singleton meta class and use the _ call _ method to simulate the behavior of the function. When constructing Class A and setting its meta class to Singleton, the behavior of class object A is as follows:

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

When creating an instance of A, A () = Singleton (name, bases, class_dict) () = Singleton (name, bases, class_dict ). _ call _ (). In this way, all instances of A are directed to the attribute _ instance of A. this method is actually the same as method 1.

Method 4

The module in python is loaded only once in the program, and itself is a singleton. You can directly write a module and write the methods and attributes you need into the module as global variables for functions and module scopes. you do not need to write classes at all.

There are also some methods that combine 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 sys. modules to ensure that they are Module objects. We use this to bind modules to a class object and will bind them to the same object in the future.

Store the code in single. py:

>>> import single>>> single.a=1>>> single.a=2

ConstError

>>> Del single.

ConstError

Method 5

The simplest method:


class singleton(object):    passsingleton=singleton()

Bind the name singleton to the instance, and singleton is the unique 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.