Hi Pythonistas!,
If you think __init__ is Python’s constructor, think again!. Python’s real constructor is __new__, not __init__.Let’s clear up the confusion!
__new__ – The Actual Constructor
Creates the object (allocates memory).
Runs before __init__.
Returns the newly created instance.
Used for Singletons, Immutable objects, and Metaclasses.
Example of __new__ Alone
class Example:
def __new__(cls):
print("Inside __new__")
instance = super().__new__(cls) # Create the object
return instance
obj = Example()
Output
Inside __new__
✅ No __init__, but object still gets created!
__init__ – Just an Initializer
Does NOT create the object.
Runs after __new__.
Only initializes attributes of an already existing object.
Example of __init__ Alone
class Example:
def __init__(self):
print("Inside __init__")
self.value = 42 # Initialize attributes
obj = Example()
Output:
Inside __init__
✅ Object was already created before __init__ ran.
How __new__ and __init__ Work Together
class Example:
def __new__(cls):
print("Inside __new__")
instance = super().__new__(cls)
return instance
def __init__(self):
print("Inside __init__")
self.value = 42
obj = Example()
Output:
Inside __new__
Inside __init__
✅ First, __new__ creates the object. Then, __init__ initializes it.
When Should You Use __new__?
Use __new__ when you need control over object creation, such as:
- Singleton Pattern (only one instance should exist)
- Immutable Objects (like tuple, str)
- Metaclasses (custom class creation behavior)
Key Differences at a Glance
Feature | __new__ (Constructor) |
__init__ (Initializer) |
---|---|---|
Purpose | Creates the object | Initializes the object |
When does it run? | Before object is created | After object is created |
Return Type | Must return an instance of the class | Returns nothing (None ) |
Use case | Singleton, Metaclasses, Immutable Objects | Normal object initialization |
__new__ is the real constructor in Python, while __init__ just sets up the object. Please share your valuable suggestions with afsal@parseltongue.co.in