🐍 Python Intermediate

What is Python's __init__, __new__, and __del__?

Answer

__new__(cls, *args, **kwargs) is called before __init__ — it creates and returns a new instance of the class. Normally you do not override it; it is used for implementing singletons, flyweight patterns, or customizing immutable type creation (subclassing int, str, tuple). __init__(self, *args, **kwargs) initializes the already-created instance — this is the constructor you normally override. __del__(self) is called when the object is about to be garbage collected (finalizer). It is unreliable — do not count on it for critical cleanup (use context managers instead). The sequence: __new__ creates the object → __init__ initializes it → (object used) → __del__ finalizes it. The GC calls __del__ at some point after all references are gone, but timing is not guaranteed.