Code Explanation:
๐น 1. Defining Class A
class A:
x = "A"
Creates a base class A
Defines a class variable x with value "A"
All subclasses inherit this unless they override it
๐น 2. Defining Class B (Overrides x)
class B(A):
x = "B"
B inherits from A
Defines its own class variable x
This overrides A.x inside class B
๐ Now:
B.x → "B"
๐น 3. Defining Class C (Overrides x)
class C(A):
x = "C"
C also inherits from A
Defines its own x
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
Does not define x
Normally, Python would use MRO to decide between B.x and C.x
๐ MRO of D:
D → B → C → A → object
๐น 5. Creating an Instance of D
d = D()
Creates an object d
At this moment:
d has no instance attribute x
Accessing d.x would follow MRO and give "B"
๐น 6. Assigning an Instance Attribute
d.x = "X"
Creates an instance variable x inside d
Stored in d.__dict__
This shadows all class variables named x
๐ Instance attributes have higher priority than:
Class attributes
Inherited attributes
MRO rules
๐น 7. Accessing d.x
print(d.x)
Attribute lookup order:
Instance dictionary (d.__dict__) → ✅ finds "X"
Class D → not checked
Class B, C, A → not checked
✅ Final Output
X

0 Comments:
Post a Comment