Code Explanation:
๐น 1. Class Definition
class Test:
This line defines a class named Test.
A class is a blueprint used to create objects.
๐น 2. Constructor Method (__init__)
def __init__(self):
self.count = 0
__init__ is a constructor, automatically called when an object is created.
self refers to the current object instance.
self.count = 0 initializes a variable count and sets it to 0.
๐น 3. Callable Method (__call__)
def __call__(self):
__call__ makes the object behave like a function.
This means you can use obj() instead of calling a method explicitly.
Inside __call__
self.count += 1
Each time the object is called, count increases by 1.
return self.count
Returns the updated value of count.
๐น 4. Creating Object
obj = Test()
Creates an instance (object) of class Test.
The constructor runs, so count = 0.
๐น 5. Calling the Object
print(obj(), obj(), obj())
What happens step-by-step:
๐ First obj()
Calls __call__
count = 0 → 1
Returns 1
๐ Second obj()
count = 1 → 2
Returns 2
๐ Third obj()
count = 2 → 3
Returns 3
๐น Final Output
1 2 3

0 Comments:
Post a Comment