Code Explanation:
1. Defining the Class
class Counter:
A class named Counter is defined.
This class will create objects that can be called like functions.
2. Initializing Instance State
def __init__(self):
self.n = 0
__init__ is the constructor.
It runs once when an object is created.
An instance variable n is created and initialized to 0.
3. Defining the __call__ Method
def __call__(self):
self.n += 1
return self.n
__call__ makes the object callable.
Each time the object is called:
self.n is increased by 1
The updated value is returned
4. Creating an Object
c = Counter()
An object c of class Counter is created.
self.n is set to 0.
5. First Call: c()
c()
Python internally calls:
c.__call__()
self.n becomes 1
Returns 1
6. Second Call: c()
c()
self.n becomes 2
Returns 2
7. Third Call: c()
c()
self.n becomes 3
Returns 3
8. Printing the Results
print(c(), c(), c())
Prints the return values of the three calls.
9. Final Output
1 2 3
Final Answer
✔ Output:
1 2 3

0 Comments:
Post a Comment