Code Explanation:
๐น 1. Class Definition
class Test:
✅ Explanation:
A class Test is created.
It will store a list in each object.
๐น 2. Constructor (__init__)
def __init__(self, x=[]):
self.x = x
✅ Explanation:
Constructor runs when object is created.
Parameter x=[] is a default argument.
⚠️ Important:
This list is created only once
It is shared across all objects
๐น 3. Assigning to Instance
self.x = x
✅ Explanation:
Assigns the same list (x) to the object
Since x is shared → all objects refer to same list
๐น 4. Creating First Object
a = Test()
✅ What happens:
No argument passed → uses default list []
So:
a.x → []
๐น 5. Creating Second Object
b = Test()
✅ What happens:
Again uses SAME default list
So:
b.x → []
⚠️ Key Insight:
a.x is b.x → True
๐ Both refer to same list
๐น 6. Modifying List via a
a.x.append(1)
✅ Explanation:
Adds 1 to the shared list
So now:
a.x → [1]
b.x → [1]
๐น 7. Printing b.x
print(b.x)
✅ Output:
[1]
Final Output:
[1]

0 Comments:
Post a Comment