I have the following code:
class Demo:
def __new__(self):
self.__init__(self)
print("Demo's __new__() invoked")
def __init__(self):
print("Demo's __init__() invoked")
class Derived_Demo(Demo):
def __new__(self):
print("Derived_Demo's __new__() invoked")
def __init__(self):
print("Derived_Demo's __init__() invoked")
def main():
obj1 = Derived_Demo()
obj2 = Demo()
main()
I'm trying to understand the order of execution:
__new__ in the derived class is called first
why doesn't _init_ in the derived class called next?
Your code is fundamentally broken, which is why
__init__isn't being invoked as expected.Per the docs for
__new__:Your
__new__doesn't explicitly return anything, so it's returningNone.If you write it correctly (including removing explicit calls to
__init__within__new__, and explicitly delegating up the inheritance chain forDerived_Demo's__new__and__init__), you code will work as expected:Try it online!
Which outputs:
where
super()based dispatch completely runs all the__new__(s) then all the__init__(s) are run on the resulting object produced by__new__.