__init__
and __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
__new__ | __init__ |
---|---|
Controls the creation of an instance | Controls the initialization of an instance |
Invoked first before __init__ | Invoked after __new__ |
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.
Code example
In the code snippet below, __new__
contains the cls
class argument while __init__
contains the self
reference to the instance.
|
|
Output:
|
|
Increment an invoked_count
variable each time __new__
is called:
|
|
Output
|
|
Use cases
__init__
is used as a class constructor for initializing new instances.
A common use case for __new__
is implementing the singleton pattern.