liveBook · Manning

__new__

As explained in Python Workout: 50 ten-minute exercises

A Python special method responsible for creating and returning a new instance before initialization occurs.

Calling Foo(10) creates an object before __init__ assigns its attributes. The method responsible for creating and returning that instance is __new__, not __init__. section 9.5

Object creation proceeds in this order:

  • Python resolves Foo as a class and calls it with 10. section 9.5
  • __new__ creates a new Foo instance. section 9.5
  • __new__ invokes __init__ before the instance is returned. section 9.5
  • __init__ adds attributes such as self.x to the instance. section 9.5

Ordinary instance construction

class Foo: def __init__(self, x): self.x = x f = Foo(10) print(f.x) The usual pattern is to define __init__ and leave __new__ alone; redefining __new__ is rarely necessary. section 9.5

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains the creation-to-initialization sequence but stops short of implementing custom __new__.
Examples
Uses Foo(10), self.x, and diagrams tracing creation, initialization, attribute assignment, and return.
What it assumes
Assumes familiarity with classes and methods while explaining callable classes, self, and runtime attributes.
What you can do after
Evaluate ordinary construction correctly and favor __init__ over redefining __new__ in typical classes.
How it connects
Connects __new__ with __init__, classes, instances, attributes, and the LEGB rule.

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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.