Explanation:
1. Class Declaration
class Counter:
This line defines a class named Counter.
2. Class Variable (Shared Across All Calls)
x = 1
This is a class variable, not tied to any object.
Its value is shared every time the method is called.
Initial value: 1
3. Method Without self
def nxt():
Counter.x *= 2
return Counter.x
Explanation:
def nxt(): → This method does not use self because we are not creating objects.
Counter.x *= 2 → Every time the method is called, the value of x is doubled.
return Counter.x → The updated value is returned.
4. Loop That Calls the Method Several Times
for _ in range(4):
This loop runs 4 times.
5. Printing the Result Each Time
print(Counter.nxt(), end=" ")
Each loop iteration calls Counter.nxt()
The returned value is printed
end=" " keeps everything on one line with spaces
Final Output
2 4 8 16


0 Comments:
Post a Comment