0

I have the following code snippet:

class A:
    def __init__(self):
        self._a = 1


class B:
    def __init__(self):
        self._b = 2


class C(A, B):
    def __init__(self):
        super(C, self).__init__()
        self._c = 3

c = C()

The resulting object does not have the attribute _b, and in fact B's __init__() is never invoked. I expected both parents' __init__() methods to be invoked one after the other. Was I mistaken? I couldn't find contradicting info.

(I use python 3.6)

1 Answers1

-1

When you simply mention super, it is a confusion that, which parent to call, either A or B. So it naturally calls the first one and stops.

To make it invoke both the parent constructors, you have to mention it explicitly. Please refer to the code below.

class A:
    def __init__(self):
        print("a")
        self._a = 1


class B:
    def __init__(self):
        print("b")
        self._b = 2


class C(B, A):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)
        self._c = 3

c = C()

To know more about this, read the excellent answer here, https://stackoverflow.com/a/50465583/4578111

venkata krishnan
  • 1,961
  • 1
  • 13
  • 20