Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - Class Methods and Static Methods
What will be the output of this code?
class Book:
    count = 0

    def __init__(self):
        Book.count += 1

    @classmethod
    def get_count(cls):
        return cls.count

b1 = Book()
b2 = Book()
print(Book.get_count())
A0
B1
C2
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand instance creation effect

    Each time a Book instance is created, the class variable count increases by 1.
  2. Step 2: Check method call and output

    Two instances are created, so count becomes 2. The class method returns this count.
  3. Final Answer:

    2 -> Option C
  4. Quick Check:

    Class variable updated by instances = 2 [OK]
Quick Trick: Class variables shared; count increments with each instance [OK]
Common Mistakes:
  • Thinking count resets per instance
  • Confusing instance and class variables
  • Expecting error due to method call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes