Differences between the _ new _ and _ init _ methods in Python

Source: Internet
Author: User
This article mainly introduces the differences between the _ new _ and _ init _ methods in Python. It is the basic knowledge in Python learning. For more information, see python2.x, classes inherited from objects are called new classes (such as class A (object) and classes not inherited from objects are called classic classes (such as class ())

The main differences between the new and classic categories are as follows:

1. The new class object can directly obtain its own type through the _ class _ attribute: type

2. the sequence of inherited searches has changed. For classic classes that inherit multiple attributes, the attribute search sequence is as follows: first, go deep to the left side of the inheritance tree, then return, and start to find the right side (that is, the depth-first search ); search Order of new multi-inheritance attributes: horizontal search first, and then move up

Example:

Classic: The search order is (D, B, A, C)

>>> class A: attr = 1...>>> class B(A): pass...>>> class C(A): attr = 2...>>> class D(B,C): pass...>>> x = D()>>> x.attr1

New class inheritance search program is width first

New category: search order is (D, B, C,)

>>> class A(object): attr = 1...>>> class B(A): pass...>>> class C(A): attr = 2...>>> class D(B,C): pass...>>> x = D()>>> x.attr2

3. The _ slots _ built-in attribute is added to the new class. You can lock the instance attribute type to the range specified by _ slots.

4. The _ getattribute _ method is added to the new class.

5. new classes have built-in _ new _ methods, while classic classes do not have _ new _ methods, but only _ init _ methods.

Note: Python 2.x is a classic class by default. Only the explicit inheritance of objects is the new class.

Python 3. x is a new class by default (that is, the object class is the ancestor of all classes by default ), you do not need to inherit objects explicitly (you can write a classic class according to the definition of the classic class and write it in python2.x and 3 respectively. in Version x, use the dir function test.

For example:

class A():      pass    print(dir(A))

We will find that there is no _ new _ method under 2. x, and there is a method under 3. x.

Next, let's talk about the differences between the _ new _ method and _ init:

When creating an instance of a class in python, if the class has the _ new _ method, the _ new _ method is called first, __new _ method accepts the class being instantiated as the first parameter (the type of this parameter is type, which plays an important role in interactive programming of c and python, if you are interested, you can search for relevant information.) The returned value is the instance generated in this creation, that is, the first parameter self in the well-known _ init _ method. Then there is a problem. How can this instance be obtained?

Note that the _ new _ method is a descendant of the object class, therefore, if we want to rewrite the _ new _ method (note that the _ new _ method of the parent class is used during instance creation without rewriting, if the parent class does not exist, the instance can be obtained by calling the _ new _ method class of the object (which is basically the same as the default mechanism in python), for example:

class display(object):  def __init__(self, *args, **kwargs):    print("init")  def __new__(cls, *args, **kwargs):    print("new")    print(type(cls))    return object.__new__(cls, *args, **kwargs)  a=display()

Run the above code to get the following output:

new
 
  init
 

Therefore, we can draw the following conclusions:

During instance creation, the _ new _ method is called before the _ init _ method. Its first parameter type is type.

If no special processing is required, you can use the _ new _ method of the object to obtain the created instance (that is, self ).

So we can find that we can use the _ new _ method class of other classes to get this instance, as long as the class or its parent class or its ancestor has the _ new _ method.

class another(object):  def __new__(cls,*args,**kwargs):    print("newano")    return object.__new__(cls, *args, **kwargs)  class display(object):  def __init__(self, *args, **kwargs):    print("init")  def __new__(cls, *args, **kwargs):    print("newdis")    print(type(cls))    return another.__new__(cls, *args, **kwargs)  a=display()

The above output is:

newdis
 
  newanoinit
 

We found that the relationship between _ new _ and _ init _ is like this. __init _ provides raw material self for production (but this raw material source is not authentic, as above, it uses the _ new _ method class of another unrelated class to get this instance ), and _ init _ uses the raw material provided by _ new _ to perfect this object (although it does not know whether these raw materials are authentic)

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.