Bird
0
0

You want to track how many objects of class Book are currently alive. Which approach best fits this requirement?

hard📝 Application Q8 of 15
Python - Classes and Object Lifecycle
You want to track how many objects of class Book are currently alive. Which approach best fits this requirement?
AUse a class variable incremented in __init__ and decremented in __del__
BPrint a message in __init__ only
CUse a global variable unrelated to the class
DCount objects manually outside the class
Step-by-Step Solution
Solution:
  1. Step 1: Understand tracking object count

    Using a class variable allows counting all instances by updating it on creation and deletion.
  2. Step 2: Match approach to requirement

    Incrementing in __init__ and decrementing in __del__ keeps an accurate live count inside the class.
  3. Final Answer:

    Use a class variable incremented in __init__ and decremented in __del__ -> Option A
  4. Quick Check:

    Track live objects = Class variable update in lifecycle [OK]
Quick Trick: Use class variables to track instances in __init__ and __del__ [OK]
Common Mistakes:
  • Only printing messages
  • Using unrelated global variables
  • Counting outside class without sync

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes