Junior — Middle
What is the role of the __new__ method in the object creation process 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 called first when an object is created and is responsible for allocating memory for the object. Unlike __init__, which initializes an already created object, __new__ returns the object itself.
Example of usage:
class MyClass:
def __new__(cls, *args, **kwargs):
print("Creating object")
instance = super().__new__(cls)
return instance
def __init__(self, value):
print("Initializing object")
self.value = value
obj = MyClass(10)
Here, __new__ is called first to create the object, then __init__ initializes it. The __new__ method is useful when you need to control the object creation process, for example, when implementing the Singleton pattern or inheriting from immutable types.