Thursday, 19 March 2026

Python Coding challenge - Day 1085| What is the output of the following Python Code?

 


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

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (223) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (9) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (86) Coursera (300) Cybersecurity (29) data (5) Data Analysis (27) Data Analytics (20) data management (15) Data Science (326) Data Strucures (16) Deep Learning (135) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (66) Git (10) Google (50) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (264) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) pytho (1) Python (1266) Python Coding Challenge (1086) Python Mistakes (50) Python Quiz (447) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (46) Udemy (17) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)