Monday, 8 November 2021

The confusing action of super().__new__ and super().__init__ in multiple inheritance

Create a son class which has two parents:

class mon():
    def __new__(cls):
        print("i am in mon's new")
        return super().__new__(cls)
    def __init__(self):
        print("i am in mon's init")
        super().__init__()


class far():
    def __new__(cls):
        print("i am in far's new")
        return super().__new__(cls)
    def __init__(self):
        print("i am in far's init")


class son(mon,far):
    def __init__(self):
        super().__init__()

Initialize the son class to check what happened.
super().__init__() in son class will call __init__ method in mon,the __new__ method executed before __init__ in mon,super().__new__(cls) in mon ,it make the code jump into far class,the __new__ method executed before __init__ in far,the code jump back to mon to print i am in mon's init and jump to far to print i am in far's init ,so we get the below output.

son_instance = son()
i am in mon's new
i am in far's new
i am in mon's init
i am in far's init

issue1:

How can rewrite the three class structure to get such output as below when to initialize son class?

son_instance = son()
i am in mon's new
i am in mon's init
i am in far's new
i am in far's init

Delete the statement in far class:

return super().__new__(cls)

The whole three class is as below then:

class mon():
    def __new__(cls):
        print("i am in mon's new")
        return super().__new__(cls)
    def __init__(self):
        print("i am in mon's init")
        super().__init__()


class far():
    def __new__(cls):
        print("i am in far's new")

class son(mon,far):
    def __init__(self):
        super().__init__()

Initialize the son class again.

x=son()
i am in mon's new
i am in far's new

Issue2:
Why the code can't jump back to mon class ?Why can't get the following output?

x=son()
i am in mon's new
i am in far's new
i am in mon's init

If no return super().__new__(cls) in far class,it only take effect on __init__ in far class,but there is no __init__ method in far class at all,why it result in not calling __init__ method in mon class?



from The confusing action of super().__new__ and super().__init__ in multiple inheritance

No comments:

Post a Comment