Code Explanation:
1. Class Definition Phase
class Test:
x = 10
✅ What happens:
A class named Test is created.
A class variable x is defined and assigned value 10.
๐ At this point:
Test.x = 10
๐ 2. Constructor (__init__) Definition
def __init__(self):
self.x = self.x + 5
✅ What happens:
This runs every time an object is created.
self.x refers to:
First tries instance variable
If not found → falls back to class variable
๐ 3. Creating First Object (t1)
t1 = Test()
Step-by-step:
๐น Step 1: Object is created
Python creates a new object t1.
๐น Step 2: __init__ runs
self.x = self.x + 5
self.x → no instance variable yet
So Python looks at class variable → Test.x = 10
๐ Calculation:
self.x = 10 + 5 = 15
๐น Step 3: Instance variable created
Now:
t1.x = 15 (instance variable)
๐ 4. Creating Second Object (t2)
t2 = Test()
Step-by-step:
Same process repeats:
self.x → still no instance variable
Uses class variable again → 10
๐ Calculation:
self.x = 10 + 5 = 15
Now:
t2.x = 15
๐ 5. Important Concept: Class vs Instance Variable
At this point:
Variable Value
Test.x 10
t1.x 15
t2.x 15
๐ Key idea:
self.x = ... creates a new instance variable
It does NOT modify the class variable
๐ 6. Final Print Statement
print(t1.x, t2.x, Test.x)
Values:
t1.x → 15
t2.x → 15
Test.x → 10
✅ Final Output
15 15 10

0 Comments:
Post a Comment