Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q5 of Q15
Python - Object-Oriented Programming Foundations
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
B2
CError
D1
Step-by-Step Solution
Solution:
  1. Step 1: Understand class variable behavior

    The variable count is a class variable shared by all instances. Each time an object is created, Counter.count increases by 1.
  2. Step 2: Count the number of objects created

    Two objects c1 and c2 are created, so Counter.count becomes 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Class variable increments = 2 [OK]
Quick Trick: Class variables shared across all instances [OK]
Common Mistakes:
MISTAKES
  • Thinking count resets for each object
  • Confusing instance and class variables
  • Expecting an error due to variable access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes