Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q5 of Q15
Python - Classes and Object Lifecycle
What will be the output of this code?
class Counter:
    count = 0
    def __init__(self):
        Counter.count += 1

c1 = Counter()
c2 = Counter()
print(Counter.count)
A0
B1
CError: count not defined
D2
Step-by-Step Solution
Solution:
  1. Step 1: Understand class variable behavior

    count is a class variable shared by all instances.
  2. Step 2: Increment count on each object creation

    Each time Counter() is called, count increases by 1. Two objects created, so count becomes 2.
  3. Final Answer:

    2 -> Option D
  4. Quick Check:

    Class variables shared across instances = 2 [OK]
Quick Trick: Class variables shared; increment affects all instances [OK]
Common Mistakes:
MISTAKES
  • Thinking count resets per instance
  • Confusing instance and class variables
  • Expecting error due to count usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes