TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
__new__ method is a special, implicitly static method responsible for creating and returning a new instance of a class. It represents the allocation phase of the object instantiation lifecycle, executing strictly before the __init__ method, which handles the initialization phase.
When a class is called to instantiate an object, Python internally invokes __new__ to construct the instance in memory. Only if __new__ successfully returns an instance of the requested class does Python proceed to call __init__ to populate its initial state.
Syntax and Signature
cls: The first parameter is the class itself that is being instantiated. Unlike instance methods that receiveself,__new__receives the class reference.*args, **kwargs: Any positional or keyword arguments passed to the class constructor are forwarded to__new__.return: The method must explicitly return a valid object reference.
Internal Mechanics
- Invocation: When you execute
obj = MyClass(x, y), Python translates this intoinstance = MyClass.__new__(MyClass, x, y). - Delegation: To actually allocate memory,
__new__typically delegates to the baseobjectclass usingsuper().__new__(cls). - Initialization Trigger: Python inspects the return value of
__new__.- If the returned object is an instance of
cls(or a subclass), Python automatically invokes__init__(instance, x, y). - If
__new__returns an object of a completely different class, or returnsNone, the__init__method ofclsis bypassed entirely.
- If the returned object is an instance of
Execution Lifecycle Demonstration
The following code illustrates the exact sequence of operations during instantiation:Technical Constraints and Behaviors
- Implicitly Static: You do not need to decorate
__new__with@staticmethod. The Python interpreter automatically binds it as a static method at the C-API level. object.__new__Signature: While your custom__new__method accepts*argsand**kwargs, the baseobject.__new__method strictly accepts only theclsargument. Passing initialization arguments tosuper().__new__(cls, *args, **kwargs)will raise aTypeErrorin modern Python.- Immutability: Because
__new__handles the actual creation of the object before it exists in memory, it is the only mechanism available to intercept and alter the instantiation process of built-in immutable types (such astuple,int, orstr).
Master Python with Deep Grasping Methodology!Learn More





