Bird
0
0

What is the output of this code?

medium📝 Predict Output Q13 of 15
Python - Constructors and Object Initialization
What is the output of this code?
class Counter:
    def __init__(self):
        self.count = 0
    def increment(self):
        self.count += 1
        return self.count
c = Counter()
print(c.increment())
print(c.increment())
A1 2
B0 1
C1 1
D2 3
Step-by-Step Solution
Solution:
  1. Step 1: Understand the initial state and method behavior

    When Counter is created, count is 0. Each increment adds 1 and returns the new value.
  2. Step 2: Trace the two calls to increment()

    First call: count goes 0 -> 1, returns 1. Second call: count goes 1 -> 2, returns 2.
  3. Final Answer:

    1 2 -> Option A
  4. Quick Check:

    Increment adds 1 each call [OK]
Quick Trick: Track self.count changes step-by-step [OK]
Common Mistakes:
  • Assuming count resets each call
  • Confusing return values
  • Ignoring self reference updates

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes