Python single-instance mode

Source: Internet
Author: User
Tags wrapper

Study the Python simple interest mode and simply record it.

1. Class and instance creation process

From creating a class to initializing an object, you can easily divide it into four steps:

(1) Create a class from a meta class and invoke __new__ to complete the creation of the class (phase a)

(2) Initialize a class, call __init__, Initialize a class (phase B)

(3) Create an object from the class, call __new__ (phase D)

(4) Initialize an object, call __init__ (phase E)

in the diagram, phase A, phase B, phase C is done by the meta-class, and when the file is loaded, the __new__ and __init__ are called automatically, and phase E is not required. phase D, phase E is the process of creating an instance, calling __new__ and __init__ manually. In general, creating a class only instantiates a class, that is, calling __init__, and __new__ execution is hidden, mainly inheriting the __new__ method of the parent class

after talking about the creation of classes and instances, consider which phase of the four-phase control is appropriate for the singleton mode?

(1) Stage A:

The process of creating a class, that is, the creation of a class is not complete. A singleton is an instance of creation, and the creation of an instance is built on the class, and this stage class is not yet created.

(2) Stage B:

Instantiating a class, this stage class is also created and appears to have the opportunity to control the number of instances

(3) Phase D:

The creation and instantiation of the class is complete, and an instance is created, but not yet completed, and the number of instances can be controlled.

(4) Phase e:

At this stage, the object has been established, each time a class is instantiated, the object has been established, the number of instances cannot be controlled.

Simply put, stage a (the process of creating a class) is not established, and it is not appropriate to control the number of instances. The instance of phase E (the process of class instantiation) has been created and cannot control the number of instances. In phase B (instantiating a Class) and phase D (creating an instance) it is easier to control the number of instances, which is

2. Implementing a singleton Mode

(1) Stage B (instantiation of a Class)

Mainly through the establishment of a meta-class control:

#Stage BclassSingleton_c (type):def __init__(Self, *args, * *Kwargs): Self.__instance=None Super (Singleton_c, self).__init__(*args, * *Kwargs)def __call__(Self, *args, * *Kwargs):ifSelf.__instance  isnone:self.__instance= Super (Singleton_c, self).__call__(*args, * *Kwargs)returnSelf.__instance        Else:            returnSelf.__instance    classC:__metaclass__=Singleton_cdef __init__(self):Print 'I am C'a=C () b=C ()PrintA isB#True

(2) Phase D (the process of creating an instance)

#Phase DclassSingleton_d (object):" "instance stored in the dictionary of the Sigleton_b class" "    def __new__(CLS, *args, * *Kwargs):if  notHasattr (CLS,'_instance'): Cls._instance= Super (Singleton_b, CLS).__new__(CLS, *args, * *Kwargs)returncls._instance#If you inherit other classes first, it will cause the singleton mode to failclassD (singleton_d):def __init__(self):Print 'I am D'a=D () b=D ()PrintA isB#True

(3) Phase D (the process of creating an instance)---a pseudo-singleton pattern

Each time the implemented object is different, but the shared variable

#Phase DclassSingleton_d1 (object): _store= {}    def __new__(CLS, *args, * *Kwargs): obj= Super (SINGLETON_B1, CLS).__new__(CLS, *args, * *Kwargs)Printcls, obj, id (cls._store), id (obj._store), id (singleton_b1._store) obj.__dict__=Cls._storereturnobj#If you inherit other classes first, it will cause the singleton mode to failclassF (SINGLETON_D1):def __init__(self, name): Self.name=NAMEF1= F (' Python') F2= F (' Singleton')PrintF1 isF2#False

(4) Decorative device

defSingleton (CLS): obj= {}    defWrapper (*args, * *Kwargs):ifCls not inchObj:obj[cls]= CLS (*args, * *Kwargs)returnObj[cls]returnWrapper@singletonclassFoo (object):PassF1=Foo () F2=Foo ()PrintF1 isF2#True

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.