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 viasuper().__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 returnNone- 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, andcopy/picklecreate 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__.