Code Explanation:
๐น 1. Defining the Class
class A:
Creates a class named A
By default, it inherits from object
๐น 2. Defining the Constructor (__init__)
def __init__(self):
self.x = 0
__init__ runs every time a new object is created
self refers to the current object
self.x = 0 creates an instance variable
Each object gets its own separate x
๐ Important:
x is not shared between objects.
๐น 3. Defining the __call__ Method
def __call__(self):
__call__ is a magic method
Allows an object to be called like a function
Writing a() is the same as calling:
a.__call__()
๐น 4. Updating the Instance Variable
self.x += 1
Increments the object’s own x
Does not affect any other object
๐น 5. Returning the Value
return self.x
Returns the updated value of the instance variable
๐น 6. Creating the First Object
a = A()
Calls __init__
a.x is initialized to 0
๐น 7. Creating the Second Object
b = A()
Calls __init__ again
b.x is also initialized to 0
a and b are independent objects
๐น 8. Calling the Objects
print(a(), b(), a())
Step-by-step execution:
a()
a.x becomes 1
Returns 1
b()
b.x becomes 1
Returns 1
a()
a.x becomes 2
Returns 2
✅ Final Output
1 1 2

0 Comments:
Post a Comment