__new__ are dunder methods invoked during the creation of an object instance.
What are the differences?
__new__is used to control the creation of a new instance
__init__is used to control the initialization of an instance
|Controls the creation of an instance||Controls the initialization of an instance|
|Invoked first before ||Invoked after |
|Returns an instance of the class||Returns nothing|
__new__ is the first step of an instance creation and is responsible for returning a new instance of the class.
In contrast, the
__init__ function initializes the instance after its creation.
In the code snippet below,
__new__ contains the
cls class argument while
__init__ contains the
self reference to the instance.
invoked_count variable each time
__new__ is called:
__init__ is used as a class constructor for initializing new instances.
A common use case for
__new__ is implementing the singleton pattern.