Code Explanation:
class A:
x = "A"
Creates base class A
Defines a class attribute x with value "A"
All subclasses inherit this attribute unless overridden
๐น 2. Defining Class B (Overrides x)
class B(A):
x = None
B inherits from A
Redefines x and assigns it None
This overrides A.x inside class B
๐ Important:
Setting x = None is still a valid override, not a removal.
๐น 3. Defining Class C (No Override)
class C(A):
pass
C inherits from A
Does not define x
So C.x is inherited from A
๐ C.x → "A"
๐น 4. Defining Class D (Multiple Inheritance)
class D(B, C):
pass
D inherits from both B and C
Does not define x
Python must decide which parent’s x to use
➡️ Python uses Method Resolution Order (MRO)
๐น 5. MRO of Class D
D.mro()
Result:
[D, B, C, A, object]
๐ Attribute lookup follows this order:
D
B
C
A
object
๐น 6. Attribute Lookup for D.x
print(D.x)
Step-by-step:
D → ❌ no x
B → ✅ x = None found
Lookup stops immediately
๐ Python does not continue to C or A
✅ Final Output
None

0 Comments:
Post a Comment