_ New _ init _ difference, __new ___ init _ difference

Source: Internet
Author: User

_ New _ init _ difference, __new ___ init _ difference

1 class A(object):2     def __init__(self,*args, **kwargs):3         print "init A"4     def __new__(cls,*args, **kwargs):5         print "new A %s"%cls6      #return super(A, cls).__new__(cls, *args, **kwargs)7         return object.__new__(cls, *args, **kwargs)

Description

1. Only new classes inherited from objects have _ new __

2. _ new _ must have at least one cls parameter representing the current class. This parameter is automatically recognized by the Python interpreter during instantiation.

3. The value of _ new _ must have a return value and return the instantiated instance. Pay special attention to this when implementing _ new _ on your own, you can return an instance of the parent class (through super (current class name, cls) _ new _, or an instance of the object _ new _.

4. _ init _ has a parameter self, which is the instance returned by _ new, __init _ other initialization actions can be completed on the basis of _ new _, __init _ does not need to return values.

5. If _ new _ creates an instance of the current class, the _ init _ function is automatically called, the first parameter of the _ new _ function called in the return statement is cls to ensure that it is the current class instance. If it is the class name of another class ,; in this case, instances of other classes are actually returned. In fact, the _ init _ function of the current class will not be called, nor the _ init _ function of other classes will be called.

 

The sequence of calls when the hierarchy is derived

1 class B(A):2     def __init__(self,*args, **kwargs):3         print "init B"4     def __new__(cls,*args, **kwargs):5         print "new B %s"%cls6      #return super(B, cls).__new__(cls, *args, **kwargs)7         return object.__new__(cls, *args, **kwargs)

 

1. When _ new _ () is not redefined during subclass definition, Python calls the _ new _ () of the direct parent class of the class by default __() method to Construct an instance of this class. If the parent class of this class is not overwritten _ new _ (), it will be traced back to the _ new _ () of the object according to this rule __() method, because object is the base class of all new classes.

2. If the _ new _ () method is rewritten in the subclass, you can select any other new class (it must be a new class, only new classes must have _ new _ (), because all new classes are descendants of objects, while classic classes do not have the _ new _ () method) the _ new _ () method of to create an instance, including all the previous generations and descendant classes of this new class, as long as they do not cause recursive endless loops. You cannot call your own _ new __, which is definitely an endless loop.

3. For the _ init __of The subclass, the calling rules are the same as those of _ new _. Of course, if the _ init _ function of the subclass and its parent class both wants to call, you can call the _ init _ function of the parent class in the _ init _ function of the subclass.

4. When using the _ init _ function, do not customize the _ new _ function, because the two features are quite different in inheritance and derivation.

 

_ New _

1. The _ new _ method is mainly used when you inherit some immutable classes (such as int, str, tuple ), it provides you with a way to customize the instantiation process of these classes.

If we need an integer that is always positive, we may write this code by integrating int.

1 class PositiveInteger(int):2     def __init__(self, value):3         super(PositiveInteger, self).__init__(self, abs(value))4 5 6 i = PositiveInteger(-3)7 print i

But after running it, we will find that the result is not what we thought at all, and we have got-3. This is because for an immutable object such as int, we only need to overload its _ new _ method to play a custom role.
Here is the modified Code:

class PositiveInteger(int):    def __new__(cls, value):        return super(PositiveInteger, cls).__new__(cls, abs(value))i = PositiveInteger(-3)print i

By reloading the _ new _ method, we have implemented the required functions.

2. Implementation Singleton

In fact, when we understand the _ new _ method, we can also use it to do other interesting things, such as implementing singleton in design patterns ).
Because the process generated after each class instantiation is controlled by _ new _, we can easily implement the singleton mode by reloading the _ new _ method.

Class Singleton (object): def _ new _ (cls): # The key lies in this. During each instantiation, we will only return the same instance object if not hasattr (cls, 'instance'): cls. instance = super (Singleton, cls ). _ new _ (cls) return cls. instanceobj1 = Singleton () obj2 = Singleton () obj1.attr1 = 'value1' print obj1.attr1, obj2.attr1print obj1 is obj2

Output result:
Value1 value1
True
We can see that obj1 and obj2 are the same instance.

class Singleton(object):    __instance = None    def __init__(self, *args, **kwargs):        pass    def __new__(cls, *args, **kwargs):        if not cls.__instance:            # if not hasattr(cls, 'instance'):            cls.__instance = super(Singleton, cls).__new__(cls, *args, **kwargs)            cls.__instance.aa = args[0]            print type(cls), type(cls.__instance), type(cls.__instance.aa)        return cls.__instanceobj1 = Singleton(1, 2, 3, b=2)obj2 = Singleton(1, 2, 3, b=2)obj1.attr1 = 'value1'obj2.attr2 = 'value2'print obj1.attr1, obj1.attr2print obj1 is obj2print obj1.aa, obj2.attr1 

Result:
<Type 'type'> <class '_ main _. Singleton'> <type 'int'>
Value1 value2
True
1 value1

 

3. Implement custom metaclass.

 

 

Reference link:

Http://www.cnblogs.com/ifantastic/p/3175735.html

Https://my.oschina.net/leejun2005/blog/207371

 

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.