Python interview questions five (the difference between __init__ and __new__)

  • __init__ is the initialization method. It is called by default immediately after the object is created, and it can receive parameters
  1. __new__ must have at least one parameter cls, representing the current class, this parameter is automatically recognized by the Python interpreter when it is instantiated

  2. __new__ must have a return value and return the instantiated instance. This should be paid special attention when implementing __new__. You can return the instance of __new__ from the parent class (through super (current class name, cls)) Directly an instance of object __new__

  3. __init__ has a parameter self, which is the instance returned by this __new__. __init__ can complete some other initialization actions on the basis of __new__, and __init__ does not require a return value

  4. If __new__ creates an instance of the current class, it will automatically call the __init__ function. The first parameter of the __new__ function called in the return statement is cls to ensure that it is the current class instance. Name, then what is actually created and returned is an instance of another class, in fact, it will not call the __init__ function of the current class, nor will it call the __init__ function of other classes.

Published 44 original articles · liked 0 · visits 1226

Guess you like

Origin blog.csdn.net/weixin520520/article/details/105335433