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?

  1. __new__ is used to control the creation of a new instance
  2. __init__ is used to control the initialization of an instance
__new____init__
Controls the creation of an instanceControls the initialization of an instance
Invoked first before __init__Invoked after __new__
Returns an instance of the classReturns 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Example:
    def __new__(cls, *args, **kwargs):
        print("__new__")
        return super().__new__(cls, *args, **kwargs)

    def __init__(self):
        print("__init__")


e = Example()

Output:

1
2
__new__
__init__

Increment an invoked_count variable each time __new__ is called:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Example:
    invoked_count = 0

    def __new__(cls, *args, **kwargs):
        Example.invoked_count += 1
        return super().__new__(cls, *args, **kwargs)

    def __init__(self):
        print(Example.invoked_count)


e1 = Example()
e2 = Example()

Output

1
2
1
2

Use cases

__init__ is used as a class constructor for initializing new instances.

A common use case for __new__ is implementing the singleton pattern.