Code Explanation:
๐น 1️⃣ Defining Class A
class A:
Creates a class named A.
Objects created from this class will inherit its attributes.
๐น 2️⃣ Defining a Class Variable
x = 5
x is a class variable.
It belongs to the class A, not to individual objects.
Internally:
A.x = 5
All objects can access it unless they override it.
๐น 3️⃣ Creating the First Object
a = A()
Creates an instance named a.
At this moment:
a.__dict__ = {}
The object has no instance attributes yet.
But it can access:
A.x
๐น 4️⃣ Creating the Second Object
b = A()
Creates another instance named b.
Same situation:
b.__dict__ = {}
No instance attributes yet.
๐น 5️⃣ Assigning a Value to a.x
a.x = 20
This is the most important line.
Python does NOT modify the class variable.
Instead it creates an instance variable inside object a.
Internally:
a.__dict__ = {'x': 20}
Now:
a.x → instance attribute
A.x → class attribute
The class variable remains unchanged.
๐น 6️⃣ Printing Values
print(A.x, b.x, a.x)
Now Python evaluates each part.
Step 1: A.x
Accessing the class variable directly:
A.x → 5
Step 2: b.x
Lookup order:
1️⃣ Check instance dictionary
b.__dict__
No x found.
2️⃣ Check class attributes
A.x
Found:
5
So b.x = 5.
Step 3: a.x
Lookup order:
1️⃣ Instance dictionary
a.__dict__ = {'x': 20}
Found immediately.
So Python returns:
20
✅ Final Output
5 5 20

0 Comments:
Post a Comment