0

I wonder hot it comes in such order that enter C enter A leave A leave C ? Who called C.__init__() ?Why is it right after B before A?

class A():
    def __init__(self):
        print('enter A')
        print('leave A')


class B(A):
    def __init__(self):
        print('enter B')
        super().__init__()
        print('leave B')


class C(A):
    def __init__(self):
        print('enter C')
        super().__init__()
        print('leave C')


class D(B, C):
    def __init__(self):
        print('enter D')
        super().__init__()
        print('leave D')


d = D()

The result is as following:

enter D
enter B
enter C
enter A
leave A
leave C
leave B
leave D
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Shengxin Huang
  • 647
  • 1
  • 11
  • 25
  • See https://en.wikipedia.org/wiki/C3_linearization, which guarantees that the method resolution order satisfies two conditions: 1) each class precedes its parents, and 2) the order of base classes is preserved. In this case, `D` precedes `B` and `C`, `B` and `C` both precede `A`, `A` precedes `object`, and `B` precedes `C`. – chepner Jul 24 '19 at 01:38

1 Answers1

0

It's because of the super().__init__'s location, it's in the middle of the two print functions, this will send it to another class before your print for leaving the class, so do:

class A():
    def __init__(self):
        print('enter A')
        print('leave A')

class B(A):
    def __init__(self):
        print('enter B')
        print('leave B')
        super().__init__()

class C(A):
    def __init__(self):
        print('enter C')
        print('leave C')
        super().__init__()

class D(B, C):
    def __init__(self):
        print('enter D')
        print('leave D')
        super().__init__()


d = D()

Output:

enter D
leave D
enter B
leave B
enter C
leave C
enter A
leave A

Also why B before A, because it processes the two sub-classes first, see @chepner's comment for more info.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114