Code Explanation:
๐น 1. Class Definition
class Test:
✅ Explanation:
A class named Test is created.
Inside this class:
A class variable x
A constructor __init__
are defined.
๐น 2. Class Variable Creation
x = []
✅ Explanation:
x is a class variable
It belongs to the class itself, NOT individual objects.
⚠️ Important:
This list is shared by ALL objects of the class.
๐น 3. Constructor Definition
def __init__(self, value):
✅ Explanation:
Constructor runs whenever object is created.
value receives value passed during object creation.
๐น 4. Appending Value
self.x.append(value)
✅ Explanation:
self.x first searches:
Instance variable
Then class variable
Since object has no own x,
Python uses class variable:
Test.x
๐น 5. Creating First Object
a = Test(1)
๐ What happens:
Constructor runs:
self.x.append(1)
Class list becomes:
[1]
๐น 6. Creating Second Object
b = Test(2)
๐ What happens:
Again constructor runs:
self.x.append(2)
Since same class list is used:
[1, 2]
๐น 7. Printing Values
print(a.x, b.x)
✅ Explanation:
Both:
a.x
b.x
point to SAME class variable.
So both print:
[1, 2]
๐ฏ Final Output
[1, 2] [1, 2]

0 Comments:
Post a Comment