Skip to the solution
MediumDSA12 min read

What is the difference between __new__ and __init__?

877 views

The problem

Question presented to candidate: "When I write Point(3, 4), Python calls both __new__ and __init__. What does each one do, in what order, and when would you ever override __new__ instead of just writing an __init__?"

What a strong answer should cover:

  • __new__(cls, ...) runs first: it receives the class, creates the object (normally via super().__new__(cls)) and returns it; it is implicitly a static method
  • __init__(self, ...) runs second on the object __new__ returned, sets its attributes and must return None
  • The glue is type.__call__: it calls __new__, and only calls __init__ if the result is an instance of the class (a subclass counts)
  • When __new__ is the right tool: subclassing immutable types (int, float, str, tuple), instance caching or singletons, and returning a different (sub)class
  • Gotchas: a cached instance still has __init__ re-run on every call, object.__new__ accepts only the class, and copy / pickle create objects through __new__ without calling __init__

Code / implementation expected: Optional β€” a class that prints from both methods to show the order, plus one immutable subclass that needs __new__.

  • new
  • init

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonThe two steps of construction and the rules that connect them
PythonWhen you need __new__: immutable subclasses, instance caching, copy and pickle

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 62 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does heapq work in Python?

Continue