Python inheritance mro() quirk

34 views Asked by At

Can anyone explain why the mro depth first traversal does this?

If my parent class inherits from two middle classes that both inherit from the same origin class, then the order of resolution follows the mro list. Seems fine...


class Origin1:
    def hello(self):
        print("Hello from Origin1")


class Middle1(Origin1):
    def hello(self):
        super().hello()
        print("Hello from Middle1")


class Middle2(Origin1):
    def hello(self):
        super().hello()
        print("Hello from Middle2")


class Parent(Middle1, Middle2):
    def hello(self):
        super().hello()
        print("Hello from Parent")


p = Parent()
p.hello()

# Hello from Origin1
# Hello from Middle2
# Hello from Middle1
# Hello from Parent
#[
#<class '__main__.Parent'>, 
#<class '__main__.Middle1'>, 
#<class '__main__.Middle2'>, 
#<class '__main__.Origin1'>, <—-starts here
#<class 'object'>
#]

However, if my two middle classes have a different origin class, then only Middle1/Origin1 process hello() and the other two are ignored. Why would Middle2.hello() evaluate on the first example but not the second?

class Origin1:
    def hello(self):
        print("Hello from Origin1")


class Origin2:
    def hello(self):
        print("Hello from Origin2")


class Middle1(Origin1):
    def hello(self):
        super().hello()
        print("Hello from Middle1")


class Middle2(Origin2):
    def hello(self):
        super().hello()
        print("Hello from Middle2")


class Parent(Middle1, Middle2):
    def hello(self):
        super().hello()
        print("Hello from Parent")


p = Parent()
p.hello()
print(Parent.mro())

# Hello from Origin1
# Hello from Middle1
# Hello from Parent
# [ 
#     < class '__main__.Parent' > , 
#     < class '__main__.Middle1' > , 
#     < class '__main__.Origin1' > , <——starts here 
#     < class '__main__.Middle2' > , <—-ignores this
#     < class '__main__.Origin2' > , <—-and this
#     < class 'object' > 
# ]
0

There are 0 answers