Code Explanation:
1. Defining the class
class Counter:
This line defines a class named Counter.
2. Class variable
x = 0
x is a class variable.
It is shared by all instances of the class.
Initially, its value is 0.
3. Defining an instance method
def inc(self):
inc is an instance method.
self refers to the object that calls the method.
4. Updating the class variable
type(self).x += 1
type(self) refers to the class of the object (Counter).
This line increments the class variable x, not an instance variable.
Using type(self) instead of Counter makes the method work correctly with subclasses.
5. Creating the first object
a = Counter()
An instance a of Counter is created.
a does not have its own x; it refers to the class variable.
6. Creating the second object
b = Counter()
Another instance b is created.
Both a and b share the same class variable x.
7. Calling the method
a.inc()
inc() is called on instance a.
The class variable x is incremented from 0 to 1.
Since x is shared, the change is visible to all instances.
8. Printing the values
print(a.x, b.x)
Python looks for x:
In the instance
Then in the class
Both a.x and b.x refer to the same class variable.
So both print the same value.
✅ Final Output
1 1

0 Comments:
Post a Comment