1

I am curious why this code:

class BaseClassA(object):
    def __init__(self):
        print('A1')
        # super().__init__()
        print('A2')

class BaseClassB(object):
    def __init__(self):
        print('B1')
        # super().__init__()
        print('B2')

class ChildClass(BaseClassA, BaseClassB):
    pass

c = ChildClass()

Prints:

A1
A2

And not (as I was expecting):

A1
A2
B1
B2

Now if you uncomment those two lines containing call to __init__() from super class you will get:

A1
B1
B2
A2

Which seems for me like super().__init__() called from BaseClassA calls __init__() from BaseClassB. Can you explain this strange behavior to me?

Edit: I saw this question, but I still don't know why __init__ method of one base class (A) influences call of __init__ from another base class (B)

bercik
  • 816
  • 1
  • 9
  • 18
  • 1
    Python doesn't automatically call all parent classes' `__init__` methods for you. Imagine if `BaseClassA` and `BaseClassB` both had a `foo` method. Would you expect `ChildClass().foo()` to call _both_ inherited `foo` methods? Of course you wouldn't, and exactly the same thing happens when your `__init__` is called. Since your `ChildClass` doesn't have an `__init__` method, python ends up calling the `__init__` you've inherited from `BaseClassA`. If you want to call both of them, you have to write code that does that. – Aran-Fey Apr 13 '18 at 12:09
  • 1
    See [this answer](https://stackoverflow.com/a/30187306/1222951) to understand why the `super().__init__()` in `BaseClassA` calls `BaseClassB.__init__`. – Aran-Fey Apr 13 '18 at 12:13
  • But why super().__init__() from BaseClassA calls BaseClassB.__init__()? BaseClassA knows __nothing__ about BaseClassB. – bercik Apr 13 '18 at 12:13

0 Answers0