Sobes.tech
Junior — Middle

Can you explain the purpose and operation of the __new__ method in Python?

sobes.tech AI

Answer from AI

The __new__ method in Python is responsible for creating a new instance of a class. It is a static method that is called before __init__ and allocates memory for the object.

Main points:

  • __new__ receives the class as its first argument and should return a new object of that class (usually called with super().__new__(cls)).
  • It is used when you need to control the object creation process, for example, when implementing the Singleton pattern or creating immutable objects.
  • After the object is created, __init__ initializes it.

Example:

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

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

obj = MyClass(10)

Output:

Creating an object
Initializing object