Unlike other programming languages most of which having just one constructor in OOP, Python additionally contains an extra dunder method named __new__
when constructing a class.
For a long period, I'm confused the difference between the two, and why Python needs an extra constructor.
So I spent some time to figure out.
In my understanding, the most vital difference is __new__
returns an instance object, while __init__
returns None
.
So if you need to change the procedure of which instance should be used when creating a new object, you need to implement a custom __new__
.
A typical usage is singleton:
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
which ensures there will be a globally unique instance for all invocations to that class.
From another perspective, __init__
can only manipulate an existing instance (object), and it fails to create one from scratch.
Besides, from their names, __init__
is responsible for initializing, while __new__
tackles creation.