Code Explanation:
1. Class Definition
class Counter:
A class named Counter is created.
This class will contain a class variable and a class method.
2. Class Variable
count = 1
count is a class variable.
It belongs to the class itself, not to individual objects.
Initial value is 1.
All instances and the class share the same variable.
3. Class Method Definition
@classmethod
def inc(cls):
cls.count += 2
@classmethod means the method receives the class (cls), not an object (self).
Inside the method:
cls.count += 2 increases the class variable by 2 each time the method is called.
4. First Call to Class Method
Counter.inc()
Calls the class method inc().
count was 1, now increased by 2 → becomes 3.
5. Second Call to Class Method
Counter.inc()
Another call to the class method.
count was 3, now increased by 2 → becomes 5.
6. Printing the Final Value
print(Counter.count)
Accesses the class variable count.
Current value is 5.
Output:
5
Final Output
5
.png)

0 Comments:
Post a Comment