Sobes.tech
Junior — Middle

What is the difference between __new__ and __init__ methods in the process of creating and initializing objects in Python?

sobes.tech AI

Answer from AI

The __new__ and __init__ methods in Python are responsible for different stages of object creation:

  • __new__(cls, ...) — this is a class method that is responsible for creating a new instance. It is called first and should return a new object of the class (usually called with super().__new__(cls)).

  • __init__(self, ...) — this is an instance method that is responsible for initializing an already created object. It is called after __new__ and sets up the object's attributes.

Example:

class MyClass:
    def __new__(cls, *args, **kwargs):
        print("Creating an object")
        instance = super().__new__(cls)
        return instance

    def __init__(self, value):
        print("Initializing the object")
        self.value = value

obj = MyClass(10)

The output will be:

Creating an object
Initializing the object

Thus, __new__ is responsible for allocating memory and creating the object, while __init__ is responsible for setting up its state.