How to Use __new__ in Python: Syntax and Examples
In Python,
__new__ is a special method used to create a new instance of a class before __init__ initializes it. You override __new__ when you need to control how objects are created, especially for immutable types.Syntax
The __new__ method is a static method that takes the class as its first argument, followed by any other arguments used to create the instance. It must return a new instance of the class (usually by calling super().__new__(cls)).
- cls: The class being instantiated.
- *args, **kwargs: Arguments passed to the constructor.
- Returns a new instance of
cls.
python
def __new__(cls, *args, **kwargs): instance = super().__new__(cls) # custom creation logic here return instance
Example
This example shows how to override __new__ to print a message when creating an object and then initialize it with __init__.
python
class MyClass: def __new__(cls, *args, **kwargs): print("Creating instance...") instance = super().__new__(cls) return instance def __init__(self, value): print("Initializing instance...") self.value = value obj = MyClass(10) print(obj.value)
Output
Creating instance...
Initializing instance...
10
Common Pitfalls
Common mistakes when using __new__ include:
- Not returning the new instance from
__new__, which causes__init__not to run. - Using
__new__unnecessarily for mutable objects where__init__is enough. - Forgetting that
__new__is a static method and must accept the class as the first argument.
python
class Wrong: def __new__(cls): print("Creating instance but not returning it") def __init__(self): print("Initializing") # This will raise an error because __new__ returns None try: obj = Wrong() except TypeError as e: print(e) class Right: def __new__(cls): print("Creating instance and returning it") return super().__new__(cls) def __init__(self): print("Initializing") obj = Right()
Output
Creating instance but not returning it
__init__() missing 1 required positional argument: 'self'
Creating instance and returning it
Initializing
Quick Reference
Use __new__ to control object creation, especially for immutable types like tuples or strings. Always return the new instance. Use __init__ for setting up instance attributes after creation.
| Method | Purpose | When to Use |
|---|---|---|
| __new__(cls, *args, **kwargs) | Create and return a new instance | Control instance creation, immutable objects |
| __init__(self, *args, **kwargs) | Initialize instance attributes | Set up after creation |
Key Takeaways
Override __new__ to customize how a new object is created before initialization.
__new__ must return the new instance; otherwise, __init__ will not run.
Use __new__ mainly for immutable types or special creation logic.
For most cases, __init__ is enough to initialize objects after creation.
Remember __new__ is a static method and receives the class as the first argument.