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
data = []
data is a class variable.
It belongs to the class A, not to individual objects.
Internally Python stores:
A.data = []
This single list will be shared by all instances.
๐น 3️⃣ Creating 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.data
๐น 4️⃣ Creating Second Object
b = A()
Creates another instance b.
Now:
a.__dict__ = {}
b.__dict__ = {}
Both objects still refer to the same class variable:
A.data
๐น 5️⃣ Modifying the List Through a
a.data.append(5)
Python does attribute lookup:
1️⃣ Check instance dictionary
a.__dict__
No data found.
2️⃣ Check class attributes
A.data
Found the list.
So Python runs:
A.data.append(5)
The list becomes:
[5]
Since the list belongs to the class, the change affects all objects.
๐น 6️⃣ Printing b.data
print(b.data)
Lookup order:
1️⃣ Check instance dictionary
b.__dict__
No data.
2️⃣ Check class attributes
A.data
Found the list:
[5]
✅ Final Output
[5]

0 Comments:
Post a Comment