Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiple inheritance and MRO

I'm currently studying for a python exam but I don't understand MRO and linearization in Python 3 yet.

class F: pass 
class G: pass 
class H: pass
class E(G,H): pass
class D(E,F): pass 
class C(E,G): pass
class B(C,H): pass
class A(D,B,E): pass

For example in one assignment theres a question whether it is possible for E to occur BEFORE C in the linearization of class A.

How do I determine whether it is possible? How could one describe the linearization algorithm (C3) as easy as possible? I'd be really thankful for all kinds of explanations and resources on this, as I'm having a hard time understanding linearization in Python.

Thanks a lot in advance!

like image 344
Daniel Siegel Avatar asked Dec 06 '25 06:12

Daniel Siegel


2 Answers

Python looks for parents or child classes in DFS order NOT IN BFS

# This order is called Method Resolution Order (`mro()`)

class A(object):
    def dothis(self):
        print('Doing this in A')

class B(A):
    pass

class C(object):
    def dothis(self):
        print('Doing this in C')

class D(B, C):
    pass

d_instance = D()
d_instance.dothis()
# METHOD RESOLUTION ORDER
print(D.mro())

'''
OUTPUT:

# Doing this in A
# [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.A'>, <class '__main__.C'>, <class 'object'>]

    A

    |               C

    B(A)          /
        \
            D(B, C)

RESOLUTION ORDER IS (DFS) = D-B-A-C



             A

        /       \

    B(A)         C(A)
        \       /
            D(B, C)

If the same class appears in mro, the earlier occurrences get removed
D-B-A-C-A -> D-B-C-A, hence still a DFS
RESOLUTION ORDER IS (In Diamond shape) = D-B-C-A


'''
like image 167
rzskhr Avatar answered Dec 07 '25 20:12

rzskhr


Class E inherit from G and H.

classes G and H dependent (they don't inherit from anybody).

Because class E has no dependency on class C, he can be initialize before him

like image 24
omri_saadon Avatar answered Dec 07 '25 20:12

omri_saadon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!