Code Explanation:
๐น 1. Class Definition
class Test:
✅ Explanation:
A class named Test is created.
Inside this class, a class variable data is defined.
๐น 2. Class Variable Creation
data = {}
✅ Explanation:
data is a class variable
It belongs to the class itself, not individual objects.
⚠️ Important:
This dictionary is shared among ALL objects of the class.
๐น 3. Creating First Object
a = Test()
✅ Explanation:
Creates object a of class Test.
At this point:
a.data → {}
But this is actually:
Test.data
๐น 4. Creating Second Object
b = Test()
✅ Explanation:
Creates another object b.
Again:
b.data
points to same class dictionary.
๐น 5. Modifying Dictionary Using a
a.data["x"] = 1
✅ Explanation:
Adds key-value pair:
"x": 1
to shared dictionary.
Now class variable becomes:
{"x": 1}
๐น 6. Why b.data Also Changes
Since:
a.data
b.data
both refer to SAME dictionary:
Test.data
So changes made through a
are visible through b.
๐น 7. Printing b.data
print(b.data)
✅ Output:
{'x': 1}
๐ฏ Final Output
{'x': 1}

0 Comments:
Post a Comment