Both __init__ and __new__ are functions in the Python object-oriented language. Among them, __new__ is used less frequently, and __init__ is used more frequently. So what is the difference between __init__ and __new__ in Python? ?Please refer to the following introduction for details.
In Python, __init__ and __new__ are two special methods used in the object creation and initialization process. They differ in what they do and when they are executed:
1、__new__
__new__ is a special method used to create an object and is called before the object is instantiated.
The __new__ method is responsible for creating an object and returns a new object instance.
The __new__ method is a class method that must return a new object instance.
You can control the object creation process by overriding the __new__ method, such as customizing the object creation logic, returning instances of other types, and so on.
2、__init__
__init__ is a special method for object initialization that is called after the object is instantiated.
The __init__ method receives the newly created object instance as its first parameter and initializes the properties of the object within the method.
The __init__ method is usually used to set the initial state of the object, assign values to properties, and so on.
The __init__ method does not need to return anything, its main purpose is to initialize the object.
Summarize:
__new__ is called before the object is instantiated to create an object instance;
__init__ is called after the object is instantiated to initialize the properties of the object.
In actual use, usually we only need to rewrite the __init__ method to realize the initialization of the object, and the need to modify the __new__ method is relatively small.