Home > Backend Development > Python Tutorial > When Does `__init__()` Not Follow `__new__()` in Python Class Instantiation?

When Does `__init__()` Not Follow `__new__()` in Python Class Instantiation?

Mary-Kate Olsen
Release: 2024-12-14 14:35:15
Original
772 people have browsed it

When Does `__init__()` Not Follow `__new__()` in Python Class Instantiation?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template