Bird
0
0

What will happen when this code runs?

medium📝 Predict Output Q5 of 15
Python - Classes and Object Lifecycle
What will happen when this code runs?
class Demo:
    def __del__(self):
        print('Object destroyed')

obj = Demo()
del obj
ANo output
BPrints 'Object created'
CPrints 'Object destroyed'
DError: __del__ not called
Step-by-Step Solution
Solution:
  1. Step 1: Understand __del__ method

    The __del__ method is called when an object is about to be destroyed, printing 'Object destroyed'.
  2. Step 2: Analyze code behavior

    After creating obj, del obj deletes it, triggering __del__ and printing the message.
  3. Final Answer:

    Prints 'Object destroyed' -> Option C
  4. Quick Check:

    del triggers __del__ = Prints destruction message [OK]
Quick Trick: del calls __del__ to clean up objects [OK]
Common Mistakes:
  • Expecting __del__ to run on creation
  • Thinking __del__ runs automatically without del
  • Confusing __del__ with __init__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes