liveBook · Manning

__new__

As explained in Python Workout, Second Edition

__new__ is a Python special method that creates and returns a new instance before initialization occurs.

__new__ creates and returns a new instance before __init__ runs. Calling Foo(10) invokes __new__, which creates the object, triggers __init__, and returns the initialized instance. __init__ adds attributes; it does not create the object. Custom __new__ implementations are rarely necessary. section 10.8

Trace a simple instance

With class Foo defining __init__(self, x) and assigning self.x = x, calling f = Foo(10) creates the instance through __new__, initializes x through __init__, and makes f.x available. section 10.8

When we create an object, __new__ is invoked.
sidebar figure

Use the sequence diagrams to distinguish instance creation by __new__ from initialization by __init__ and final return to the caller. section 10.8

How Python Workout, Second Edition covers it

How deep it goes
Traces creation, initialization, and return, while deferring custom __new__ implementation as rarely necessary.
Examples
Uses Foo(10), self.x, and f.x to demonstrate creation followed by attribute initialization.
What you can do after
Understand the execution order behind class calls and avoid mistaking __init__ for the instance-creation method.
How it connects
Connects __new__ with classes, __init__, instances, attributes, and callable class invocation.

Also explained in

Compare how 3 books explain __new__ →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.