Code Explanation:
๐น 1. Creating a Class
class Test:
✅ Explanation:
A class named Test is created.
This class acts as a blueprint for creating objects.
At this moment:
Test Class Created
๐น 2. Creating a Class Variable
x = 10
✅ Explanation:
x is a class variable.
It belongs to the class itself.
Only one copy exists.
Current state:
Test
└── x = 10
๐น 3. Creating an Object
obj = Test()
✅ Explanation:
An object named obj is created.
Currently, obj has no instance variables.
Object state:
obj
└── {}
(Empty namespace)
๐น 4. Accessing obj.x Before Assignment
If we had written:
print(obj.x)
Python would search:
obj namespace ❌
Test namespace ✅
and find:
10
because x exists in the class.
๐น 5. Creating an Instance Variable
obj.x = 50
✅ Explanation:
Many beginners think this changes:
Test.x
❌ Wrong
Python creates a new variable inside the object.
Internally:
obj.__dict__["x"] = 50
Now state becomes:
Test
└── x = 10
obj
└── x = 50
๐น 6. Printing Class Variable
print(Test.x)
✅ Explanation:
Python directly accesses:
Test.x
Value:
10
Output:
10
๐น 7. Printing Object Variable
print(obj.x)
✅ Explanation:
Python searches:
obj namespace ✅
and finds:
50
No need to check class.
Output:
50
๐ฏ Final Output
10
50

0 Comments:
Post a Comment