The Singleton mode is implemented by Python through _ new _. The differences between the _ new _ and _ init _ methods are __new ___ init _

Source: Internet
Author: User

The Singleton mode is implemented by Python through _ new _. The differences between the _ new _ and _ init _ methods are __new ___ init _

Previously, I learned that the singleton mode can be implemented through the _ new _ method in Python. The code example is as follows, so I have a few questions, what is Singleton mode? _ New _ What is the method used? Is the singleton mode implemented using the _ new _ method, for example, the MyClass class below, affecting class initialization? Will it affect the instance method, class method, and static method of the class? I would like to explain my understanding of these concepts below. If you have any mistakes, I would like to express my gratitude to you.

 1 class SingleTon(object): 2     _instance = {} 3  4     def __new__(cls, *args, **kwargs): 5         if cls not in cls._instance: 6             cls._instance[cls] = super(SingleTon, cls).__new__(cls, *args, **kwargs) 7         print cls._instance 8         return cls._instance[cls] 9 10 11 class MyClass(SingleTon):12     class_val = 22

 

First of all, the Order example mode ensures that a class has only one instance, and this instance is created by itself. This instance is used in the system. The Singleton mode is a type of design mode. For more details about the design mode and Singleton mode, you can view related books and learn these things later.

 

In Python, _ new _ is used to create a class instance, _ init _ is used to initialize this instance. Since _ new _ is used to create an instance, the instance of the corresponding class needs to be returned at last. What if the instance of another class is returned? See the following code. After the following code is run, print the NoReturn _ new _ and then the other instance) the t type is <class '_ main __. other '>, you can know that if _ new _ does not return an instance of this class, the _ init _ method cannot be called. To return the instance of this class, you only need to change the following 12 lines of Other () in the codeSuper (NoReturn, cls). _ new _ (cls, * args, ** kwargs)You can.

 

 1 class Other(object): 2     val = 123 3  4     def __init__(self): 5         print 'other instance' 6  7  8 class NoReturn(object): 9 10     def __new__(cls, *args, **kwargs):11         print 'NoReturn __new__'12         return Other()13 14     def __init__(self, a):15         print a16         print 'NoReturn __init__'17 18 t = NoReturn(12)19 print type(t)

Finally, will the singleton mode implemented using the _ new _ method affect the instance methods, class methods, static methods, instance variables, and class variables? The answer is that there is no impact on the corresponding method, but if the instance is initialized with different variables and the instance variables and class variables are modified in the subsequent variables, the preceding variables will be modified accordingly, which is in line with the singleton. No matter how many variables point to this instance, they point to the same one. After an instance is generated in _ new _, the same instance is generated every time the instance object is initialized, the related methods and variables in this instance are still used in the same way as normal instances. The test code and output are as follows:

1 class MyClass (SingleTon): 2 class_val = 22 3 4 def _ init _ (self, val): 5 self. val = val 6 7 def obj_fun (self): 8 print self. val, 'obj _ fun '9 10 @ staticmethod11 def static_fun (): 12 print 'staticmethod' 13 14 @ classmethod15 def class_fun (cls): 16 print cls. class_val, 'classmethod' 17 18 19 if _ name _ = '_ main _': 20 a = MyClass (1) 21 B = MyClass (2) 22 print a is B # True23 print id (a), id (B) #4367665424 436766542424 # type verification 25 print type (a) # <class '_ main __. myclass'> 26 print type (B) # <class '_ main __. myclass'> 27 # instance method 28. obj_fun () #2 obj_fun29 B. obj_fun () #2 obj_fun30 # class method 31 MyClass. class_fun () #22 classmethod32. class_fun () #22 classmethod33 B. class_fun () #22 classmethod34 # Static Method 35 MyClass. static_fun () # staticmethod36. static_fun () # staticmethod37 B. static_fun () # staticmethod38 # class variable 39. class_val = 3340 print MyClass. class_val #2241 print. class_val #3342 print B. class_val #3343 # instance variable 44 print B. val #245 print. val #2

 

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.