Bird
Raised Fist0

Identify the error in this code related to object lifecycle:

medium📝 Debug Q14 of Q15
Python - Classes and Object Lifecycle
Identify the error in this code related to object lifecycle:
class Sample:
    def __init__(self):
        print('Init called')
    def __del__(self):
        print('Del called')

obj = Sample()
obj = None
print('Done')
ADestructor __del__ will not be called because obj is set to None
BSyntax error in class definition
CNo error; destructor will be called when obj is set to None
DConstructor __init__ will not be called
Step-by-Step Solution
Solution:
  1. Step 1: Understand what happens when obj is set to None

    Setting obj = None removes the reference to the Sample object, so it becomes eligible for garbage collection.
  2. Step 2: Confirm destructor call behavior

    When no references remain, __del__ is called, so 'Del called' will print before 'Done'.
  3. Final Answer:

    No error; destructor will be called when obj is set to None -> Option C
  4. Quick Check:

    Destructor runs when object has no references [OK]
Quick Trick: Destructor runs when last reference is removed [OK]
Common Mistakes:
MISTAKES
  • Thinking setting variable to None skips destructor
  • Confusing syntax errors with lifecycle behavior
  • Assuming constructor is skipped

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes