Difference between init and new in Python
__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.
1class Example:
2 def __new__(cls, *args, **kwargs):
3 print("__new__")
4 return super().__new__(cls, *args, **kwargs)
5
6 def __init__(self):
7 print("__init__")
8
9
10e = Example()
Output:
1__new__
2__init__
Increment an invoked_count
variable each time __new__
is called:
1class Example:
2 invoked_count = 0
3
4 def __new__(cls, *args, **kwargs):
5 Example.invoked_count += 1
6 return super().__new__(cls, *args, **kwargs)
7
8 def __init__(self):
9 print(Example.invoked_count)
10
11
12e1 = Example()
13e2 = Example()
Output
11
22
Use cases
__init__
is used as a class constructor for initializing new instances.
A common use case for __new__
is implementing the singleton pattern.