0
0
PythonComparisonBeginner · 4 min read

__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__
PurposeCreate and return a new instanceInitialize the instance after creation
Called whenBefore the instance existsAfter the instance is created
Return valueMust return the new instanceReturns None
Typical use caseControl instance creation, immutable typesSet instance attributes
Method typeStatic method (class method style)Instance method
Called onClassInstance
⚖️

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.

python
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)
Output
__new__ called __init__ called 10
↔️

__init__ Equivalent

This example focuses only on __init__ to initialize the instance after default creation.

python
class MyClass:
    def __init__(self, value):
        print("__init__ called")
        self.value = value

obj = MyClass(10)
print(obj.value)
Output
__init__ called 10
🎯

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.
Override __new__ to customize object creation, especially for immutable types.
Use __init__ to set instance attributes after creation.
__new__ must return the instance; __init__ returns None.
Most classes only need to override __init__.