In Python, the __init__  dunder method is an initialiser method that is used to initialise the attributes of an object after it is created, whereas the __new__ method is used to create the object. When we define both the __new__ and the __init__ methods inside a class, Python first calls the __new__ method to create the object and then calls the __init__ method to initialise the object’s attributes. Most programming languages (e.g. Java) require only a constructor, a special method to create + initialise objects, but Python has both a constructor and an initialiser.

New method

As stated already, when creating an object, the __new__ is called first, and it creates (returns) a new instance of the class. Python then automatically passes that instance to __init__ for initialisation. Rarely overridden unless you’re customising class creation (e.g., singleton or immutable objects).

class Dog:
    def __new__(cls, name):
        print(f'Called the __new__ method.')
        instance = super().__new__(cls)
		return instance
        
    def __init__(self, name):
        print(f"Called the __init__ method.")
        self.name = name
 
# Created an object
dog = Dog("Buddy")
Called the __new__ method.
Called the __init__ method.

Back to parent page: Python