__new__ vs __init__ in Python: Key Differences and Usage
__new__ is the method that creates a new instance of a class, while __init__ initializes the instance after it is created. __new__ returns the new object, and __init__ sets up its attributes without returning anything.Quick Comparison
This table summarizes the main differences between __new__ and __init__ in Python.
| Aspect | __new__ | __init__ |
|---|---|---|
| Purpose | Create and return a new instance | Initialize the instance after creation |
| Called when | Before the instance exists | After the instance is created |
| Return value | Must return the new instance | Returns None |
| Typical use case | Control instance creation, immutable types | Set instance attributes |
| Method type | Static method (class method style) | Instance method |
| Called on | Class | Instance |
Key Differences
__new__ is a special method responsible for creating a new object. It is called before __init__ and must return a new instance of the class (or a different class). This method is rarely overridden unless you need to control how objects are created, such as implementing singletons or immutable types like tuples.
On the other hand, __init__ is called right after the object is created to initialize its attributes. It does not create the object but sets up its state. It always returns None. Most classes override __init__ to assign values to instance variables.
In summary, __new__ handles object creation and must return the object, while __init__ handles object setup and returns nothing.
__new__ Example
This example shows how __new__ creates the instance and __init__ initializes it.
class MyClass: def __new__(cls, *args, **kwargs): print("__new__ called") instance = super().__new__(cls) return instance def __init__(self, value): print("__init__ called") self.value = value obj = MyClass(10) print(obj.value)
__init__ Equivalent
This example focuses only on __init__ to initialize the instance after default creation.
class MyClass: def __init__(self, value): print("__init__ called") self.value = value obj = MyClass(10) print(obj.value)
When to Use Which
Choose __new__ when you need to control how an object is created, such as returning an existing instance or customizing immutable objects. Use it sparingly because it deals with low-level creation.
Choose __init__ for most cases where you just want to set up or initialize the attributes of a new object. It is the standard way to prepare an instance after it is created.
Key Takeaways
__new__ creates and returns a new instance; __init__ initializes it.__new__ to customize object creation, especially for immutable types.__init__ to set instance attributes after creation.__new__ must return the instance; __init__ returns None.__init__.