Code Explanation:
๐น 1. Defining Class A
class A:
x = "A"
Creates a base class A
Defines a class variable x with value "A"
Any subclass can inherit this variable
๐น 2. Defining Class B (Inherits from A)
class B(A):
pass
B inherits from A
No x is defined in B
So B inherits A.x
๐ At this point:
B.x → "A"
๐น 3. Defining Class C (Overrides x)
class C(A):
x = "C"
C inherits from A
Defines its own class variable x
This overrides A.x inside C
๐ Now:
C.x → "C"
๐น 4. Defining Class D (Multiple Inheritance)
class D(B, C):
pass
D inherits from both B and C
No x is defined in D
Python must decide which parent’s x to use
➡️ This is where MRO (Method Resolution Order) comes into play.
๐น 5. Understanding MRO of Class D
Python calculates MRO using the C3 linearization algorithm.
D.mro()
Result:
[D, B, C, A, object]
๐ This means Python looks for attributes in this order:
D
B
C
A
object
๐น 6. Attribute Lookup for D.x
print(D.x)
Step-by-step lookup:
D → ❌ no x
B → ❌ no x (inherits but doesn’t define)
C → ✅ x = "C" found
Stop searching
✅ Final Output
C

0 Comments:
Post a Comment