r/learnpython • Crul • Jun 24 '22

I don't understand how `super(ParentOrCurrentClass, self).__init__()` works ... with multiple inheritance

Ok, I now understand how super(ParentOrCurrentClass, self).__init__() works with single inheritance.

But I don't understand the multiple inheritance case. Take this example (link to runable page, code pasted on bottom).

  • I get how ChildD().foo and ChildE().foo works, asuming that python takes the first parent class by default, which is BaseA in this case
  • I also understand how ChildG().foo works, because [EDIT: this is WRONG, see comments] super(BaseB, self).__init__() means "execute the constructor of the Parent class of BaseB", which is just Object, so self.foo = "foo Child G" is never overwritten
  • But, how is it possible that ChildF().foo returns foo Base B if we're calling super(BaseA, self).__init__() and BaseB is not a parent class of BaseA?

Thanks


Code

class BaseA():
    def __init__(self):
        self.foo = "foo Base A"

class BaseB():
    def __init__(self):
        self.foo = "foo Base B"

class ChildD(BaseA, BaseB):
    def __init__(self):
        self.foo = "foo Child D"
        super().__init__()

class ChildE(BaseA, BaseB):
    def __init__(self):
        self.foo = "foo Child E"
        super(ChildE, self).__init__()

class ChildF(BaseA, BaseB):
    def __init__(self):
        self.foo = "foo Child F"
        super(BaseA, self).__init__()

class ChildG(BaseA, BaseB):
    def __init__(self):
        self.foo = "foo Child G"
        super(BaseB, self).__init__()

def test():

    print("ChildD:", ChildD().foo)   # ChildD: foo Base A
    print("ChildE:", ChildE().foo)   # ChildE: foo Base A
    print("ChildF:", ChildF().foo)   # ChildF: foo Base B
    print("ChildG:", ChildG().foo)   # ChildG: foo Child G

test()
5 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/Crul_ Crul Jun 24 '22

Thanks a lot! This is a perfect explanation :).