Code Explanation:
1. Class Definition
class Counter:
A class named Counter is created.
It will contain a class variable and a class method.
2. Class Variable
count = 1
count is a class variable, meaning it is shared by all objects of the class.
Initially set to 1.
3. Class Method Definition
@classmethod
def inc(cls):
cls.count += 2
@classmethod
The decorator @classmethod defines a method that works on the class itself, not on an instance.
inc(cls)
cls refers to the class (not an object).
Inside the method, it modifies the class variable:
cls.count += 2
Every time inc() is called, it increases count by 2.
4. Calling the Class Method – First Call
Counter.inc()
Calls the class method directly using the class name.
count increases from 1 → 3.
5. Calling the Class Method – Second Call
Counter.inc()
Called again.
count increases from 3 → 5.
6. Printing the Final Count
print(Counter.count)
Prints the final value of the class variable count.
Output:
5
Final Output
5


0 Comments:
Post a Comment