Code Explanation:
1️⃣ Defining Class Tracker
class Tracker:
A class named Tracker is created.
Objects of this class will inherit its variables and methods.
๐น 2️⃣ Defining a Class Variable
total = 0
total is a class variable.
It belongs to the class itself, not to individual objects.
Internally:
Tracker.total = 0
All instances will use the same variable.
๐น 3️⃣ Defining Method add
def add(self):
add is an instance method.
self refers to the object calling the method (t1 or t2).
๐น 4️⃣ Updating the Class Variable
Tracker.total += 2
This increases the class variable total by 2.
Important:
We are modifying the class variable directly:
Tracker.total
So every object sees the updated value.
๐น 5️⃣ Returning the Updated Value
return Tracker.total
After incrementing, the method returns the new value of total.
๐น 6️⃣ Creating First Object
t1 = Tracker()
Creates an instance named t1.
At this moment:
Tracker.total = 0
๐น 7️⃣ Creating Second Object
t2 = Tracker()
Creates another instance t2.
Both objects share the same variable:
Tracker.total
๐น 8️⃣ Calling the Methods
print(t1.add(), t2.add(), t1.add())
Python executes each call left to right.
Step 1️⃣
t1.add()
Execution:
Tracker.total = 0 + 2
Now:
Tracker.total = 2
Return value:
2
Step 2️⃣
t2.add()
Execution:
Tracker.total = 2 + 2
Now:
Tracker.total = 4
Return value:
4
Step 3️⃣
t1.add()
Execution:
Tracker.total = 4 + 2
Now:
Tracker.total = 6
Return value:
6
✅ Final Output
2 4 6

0 Comments:
Post a Comment