Understanding the Sequence of __new__() and __init__() Execution
Python's __new__() and __init__() methods play vital roles in class instantiation. __new__() creates a new instance of a class, while __init__() initializes that instance. The expected sequence of execution is for __new__() to be called before __init__().
However, a specific scenario can alter this sequence. When implementing a custom __new__() method, it's possible to manipulate instance creation and return an existing instance instead of creating a new one. This behavior is utilized to implement patterns like the flyweight design pattern.
In such cases, you might observe __init__() being called after __new__() even though it's unexpected. __init__() is always called after __new__() unless the custom __new__() returns an existing object.
To address this, consider implementing the desired functionality in a more conventional manner, such as using a factory function. Alternatively, you could include the initialization code within the custom __new__() method. However, this approach can be considered "hacky" and is not recommended as the best practice.
The above is the detailed content of When Does `__init__()` Not Follow `__new__()` in Python Class Instantiation?. For more information, please follow other related articles on the PHP Chinese website!