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!
# 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
'''
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With