0

in Python3 i have one class that inherits two other classes. However as i see when an object is initialized only first class of it initialized also see example...

    class A:
        def __init__(self):
            print("A constructor")


    class B:
        def __init__(self):
            print("B constructor")


    class C(A, B):
        def __init__(self):
            print("C constructor")
            super().__init__()


    c = C()

This has the output:

C constructor A constructor

My questions are, why it does not call B constructor also? And is it possible to call B constructor from C class with super?

demosthenes
  • 1,151
  • 1
  • 13
  • 17

1 Answers1

1
class A:
    def __init__(self):
        print("A constructor")
        super().__init__()        # We need to explicitly call super's __init__ method. Otherwise, None will be returned and the execution will be stopped here.

class B:
    def __init__(self):
        print("B constructor")


class C(A, B):
    def __init__(self):
        print("C constructor")
        super().__init__()        # This will call class A's __init__ method. Try: print(C.mro()) to know why it will call A's __init__ method and not B's.

c = C()

Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24