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 unless it overrides it
๐น 2. Defining Class B (Inherits from A)
class B(A):
x = "B"
B inherits from A
x is redefined in B
This overrides A.x for class B and its subclasses
๐ Now:
A.x → "A"
B.x → "B"
๐น 3. Defining Class C (Inherits from A)
class C(A):
pass
C inherits from A
No x is defined in C
So C uses A.x
๐ C.x → "A"
๐น 4. Defining Class D (Multiple Inheritance)
class D(B, C):
pass
D inherits from both B and C
No attribute x is defined in D
Python must decide from which parent to take x
➡️ This is where MRO (Method Resolution Order) comes in
๐น 5. Understanding MRO of Class D
Python calculates MRO using the C3 linearization algorithm:
D.mro()
Result:
[D, B, C, A, object]
๐ Meaning:
Python searches 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 → ✅ found x = "B"
Stop searching
✅ Final Output
B

0 Comments:
Post a Comment