The key points and difficulties of classes in python3: __new__ method and __init__ method

        The construction method includes creating an object and initializing the object. In python, it is divided into two steps: first execute the __new__ method, and then execute the __init__ method;
  • __init__ is called when the instance object is created, and then sets some initial values ​​of the object properties.

  • __new__ is called before the instance is created, because its job is to create an instance and then return it, which is a static method.

That is, __new__ is called before __init__, the return value (instance) of __new__ will be passed to the first parameter of the __init__ method, and then __init__ will set some parameters for this instance.


Look again:

Summarize

  • __new__There must be at least one parameter cls, representing the class to be instantiated, this parameter is automatically provided by the Python interpreter when instantiating

  • __new__You must have a return value and return the instantiated instance. __new__You should pay special attention to this when you implement it yourself. You can return the instance from the parent class __new__, or directly from the object __new__.

  • __init__There is a parameter self, which is the __new__returned instance. __init__On __new__the basis of this, some other initialization actions can be completed __init__without returning a value.

  • We can compare it to a manufacturer. __new__The method is the initial purchase of raw materials. __init__The method is to process and initialize the commodity on the basis of raw materials.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325704136&siteId=291194637