Consider the following Python code that creates and deletes an object. What will be printed?
class MyClass: def __init__(self): print('Object created') def __del__(self): print('Object deleted') obj = MyClass() del obj print('End of program')
Think about when __init__ and __del__ methods are called.
The __init__ method runs when the object is created, printing 'Object created'. The del obj statement deletes the object, triggering __del__ and printing 'Object deleted'. Finally, 'End of program' is printed.
Choose the correct statement about when Python calls the __del__ method of an object.
Think about object lifetime and memory cleanup.
The __del__ method is called when an object is about to be destroyed, usually when no references to it remain and the garbage collector cleans it up.
Analyze the code below. What will be printed?
class Demo: def __init__(self): print('Created') def __del__(self): print('Deleted') obj1 = Demo() obj2 = obj1 del obj1 print('Deleted obj1') del obj2 print('Deleted obj2')
Remember that the object is deleted only when all references are gone.
The object is created and printed 'Created'. Deleting obj1 removes one reference but obj2 still points to the object, so __del__ is not called yet. After deleting obj2, no references remain, so __del__ runs and prints 'Deleted'. The print statements show the order.
Look at this code snippet. Sometimes 'Deleted' is not printed. Why?
class Test: def __del__(self): print('Deleted') def create(): obj = Test() create() print('Done')
Think about when Python runs garbage collection and program exit behavior.
The object obj is created inside create() and goes out of scope after the function ends. However, Python may delay garbage collection until program exit. Sometimes __del__ is not called before 'Done' is printed because the program ends before cleanup.
Choose the correct statement about exceptions raised inside the __del__ method.
Think about how Python handles errors during object destruction.
If an exception occurs inside __del__, Python does not propagate it. Instead, it prints a warning message to standard error and continues program execution. This prevents program crashes during garbage collection.