Z Chen
Z Chen

Reputation: 981

About python multiple inheritance

class base:
    def __init__(self):
        print('base')


class F0(base):
    def __init__(self):
        super().__init__()
        print("F0")


class F1(F0):
    def __init__(self):
        super().__init__()
        print("F1")


class F2(F0):
    def __init__(self):
        super().__init__()
        print("F2")


class F3(F1, F2):
    def __init__(self):
        super().__init__()
        print("F3")

# -------------------------------------
class Base_1():
    def __init__(self):
        print('base_1')

class Base_2():
    def __init__(self):
        print('base_2')
        
class Base_3(Base_1, Base_2):
    def __init__(self):
        super().__init__()
        print("base_3")


if __name__ == '__main__':
    f3 = F3()
    print(F3.mro())

    base_3 = Base_3()
    print(Base_3.mro())

Output:

base
F0
F2
F1
F3
[<class '__main__.F3'>, <class '__main__.F1'>, <class '__main__.F2'>, <class '__main__.F0'>, <class '__main__.base'>, <class 'object'>]
base_1
base_3
[<class '__main__.Base_3'>, <class '__main__.Base_1'>, <class '__main__.Base_2'>, <class 'object'>]

Point I understand:

For Base_3 class, it inherits Base_1 and Base_2. In Base_3's init function, if I call super().__init__() it only executes Base_1's init function.

Point I don't understand:

2 classes (F1, F2) have a same father class (F0) who inherits from another class (base). Then if I call super().__init__() in F3 (which inherits F1 and F2), it will execute both F1 and F2's init function.

Upvotes: 1

Views: 50

Answers (2)

Dmitriy Neledva
Dmitriy Neledva

Reputation: 864

in case of base_3 there is no MRO rules applied because base_1 and base_2 are not linked to each other by inheritance
so it means that simple inheritance tree search rules are applied in case of base_3 => when you call super in base_3 that super finds first __init__ in base_1 (cuz of base_1 is lefter - Base_3(Base_1, Base_2)) and then nothing happens, super is worked
but in case of F3 its parents F1 and F2 has the same parent F0 so it mean that F0 is inherited by F3 twice == diamond problem occures(!), and this diamond problem will be solved by MRO3 but not with simple inheritance like in case of base_3

Upvotes: 1

Bastian Venthur
Bastian Venthur

Reputation: 16570

Then if I call super().init() in F3 (which inherits F1 and F2), it will execute both F1 and F2's init function.

But that is the expected case right, since:

class F3(F1, F2):
    ...

Base_3 inherits from both classes.

Upvotes: 0

Related Questions