Code Explanation:
1. Defining the Class
class A:
Creates a class named A
By default, it inherits from object
๐น 2. Defining a Class Variable
x = 0
x is a class variable
It belongs to the class A
Initially, there is only one x shared by all objects
๐ At this point:
A.x = 0
๐น 3. Defining an Instance Method
def inc(self):
self.x += 1
inc() is an instance method
self refers to the object calling the method
self.x += 1 is the key line (important trap)
๐น 4. What Really Happens in self.x += 1
This line is equivalent to:
self.x = self.x + 1
Step-by-step:
Python looks for x in the instance
If not found, it looks in the class
Reads the value from A.x
Adds 1
Creates a new instance variable x
๐ This means:
The class variable is not modified
A new instance variable shadows it
๐น 5. Creating the First Object
a = A()
Creates object a
a has no instance variable x yet
๐น 6. Creating the Second Object
b = A()
Creates object b
Also has no instance variable x
๐น 7. Calling a.inc()
a.inc()
Uses A.x = 0
Calculates 0 + 1
Creates a.x = 1
๐ Now:
A.x = 0
a.x = 1
๐น 8. Calling b.inc()
b.inc()
Uses A.x = 0
Calculates 0 + 1
Creates b.x = 1
๐ Now:
A.x = 0
a.x = 1
b.x = 1
๐น 9. Printing the Values
print(A.x, a.x, b.x)
Lookup results:
A.x → class variable → 0
a.x → instance variable → 1
b.x → instance variable → 1
✅ Final Output
0 1 1

0 Comments:
Post a Comment