Code Explanation:
1️⃣ Defining the Class
class A:
Explanation
A class named A is created.
It will be used to create objects.
2️⃣ Creating a Class Variable
x = 5
Explanation
x is a class variable.
It belongs to the class, not to individual objects.
All objects initially share this value.
3️⃣ Creating First Object
a = A()
Explanation
Creates an instance a of class A.
a can access class variable x.
4️⃣ Creating Second Object
b = A()
Explanation
Creates another instance b.
Both a and b currently share:
x = 5
5️⃣ Modifying Variable via Object
a.x = 10
Explanation ⚠️
This does NOT change the class variable.
Instead, it creates a new instance variable x inside object a.
๐ Now:
A.x = 5 # class variable
a.x = 10 # instance variable (new)
b.x = 5 # still uses class variable
6️⃣ Printing Values
print(A.x, a.x, b.x)
Explanation
A.x → class variable → 5
a.x → instance variable → 10
b.x → no instance variable → uses class variable → 5
๐ค Final Output
5 10 5

0 Comments:
Post a Comment