__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.