Full answer
class Traced:
def __new__(cls, *args):
print("__new__", cls.__name__, args)
return super().__new__(cls)
def __init__(self, x):
print("__init__", x)
self.x = x
Traced(5)
class Celsius(float):
def __new__(cls, value):
return super().__new__(cls, round(value * 2) / 2)
print(Celsius(21.37), isinstance(Celsius(1), float))
class Colour:
_cache = {}
def __new__(cls, name):
if name not in cls._cache:
cls._cache[name] = super().__new__(cls)
return cls._cache[name]
def __init__(self, name):
print("init", name)
self.name = name
print(Colour("red") is Colour("red"))Output:
__new__ Traced (5,)
__init__ 5
21.5 True
init red
init red
TrueThe trace shows __new__ running first with the class as its first argument, then __init__ with the created instance. If __new__ returned an object that is not an instance of the class, __init__ would be skipped.
Celsius subclasses float, which is immutable: by the time __init__ runs, the float value is already fixed, so rounding must happen in __new__. The result behaves like a float with value 21.5.
Colour caches instances by name in __new__, so asking for 'red' twice returns the same object. Note that __init__ still runs on every call, even for a cached instance, which is a common surprise; keep such classes' __init__ idempotent or do all setup in __new__. Metaclasses and singletons are other places where __new__ appears.
class Traced:
def __new__(cls, *args):
print("__new__", cls.__name__, args)
return super().__new__(cls)
def __init__(self, x):
print("__init__", x)
self.x = x
Traced(5)
class Celsius(float):
def __new__(cls, value):
return super().__new__(cls, round(value * 2) / 2)
print(Celsius(21.37), isinstance(Celsius(1), float))
class Colour:
_cache = {}
def __new__(cls, name):
if name not in cls._cache:
cls._cache[name] = super().__new__(cls)
return cls._cache[name]
def __init__(self, name):
print("init", name)
self.name = name
print(Colour("red") is Colour("red"))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- __new__ creates, __init__ initialises
- Immutable subclasses set values in __new__
- __init__ is skipped if __new__ returns another type
- __init__ runs again for cached instances
- Most classes need only __init__
Common mistakes
- Trying to change an immutable value in __init__
- Forgetting to return the instance from __new__
Follow-ups
- How do metaclasses relate to __new__?
- How would you implement a singleton more simply?
Tips
- Show the call order