Implement and Test the __del__ Method
In this step, you will learn about the __del__ method. This method is called a finalizer or destructor. It is invoked when an object's reference count drops to zero, meaning it is about to be destroyed by Python's garbage collector. It is often used for cleanup tasks, like closing network connections or file handles.
You can remove a reference to an object using the del statement. When the last reference is gone, __del__ is automatically called.
Let's add a __del__ method to our Dog class to see when an object is destroyed.
Open the dog_cat.py file again. Replace the entire content of the file with the following code. This version removes the code that creates a Dog instance (to avoid creating it when the module is imported), and it adds the __del__ method to the Dog class.
## File Name: dog_cat.py
class Animal:
def __init__(self, name):
self._name = name
def say(self):
print(self._name + ' is saying something')
class Dog(Animal):
def __new__(cls, name, age):
instance = super().__new__(cls)
return instance
def __init__(self, name, age):
super().__init__(name)
self.age = age
def say(self):
print(self._name + ' is making a sound: wang wang wang...')
## Add this method to the Dog class
def __del__(self):
print(f'The Dog object {self._name} is being deleted.')
Save the dog_cat.py file.
Now, let's create a separate script to test this behavior. Open the file test_del.py from the file explorer.
Add the following code to test_del.py. This script will create two Dog instances and then delete one of them explicitly.
## File Name: test_del.py
from dog_cat import Dog
import time
print("Creating two Dog objects: d1 and d2.")
d1 = Dog('Tom', 3)
d2 = Dog('John', 5)
print("\nDeleting reference to d1...")
del d1
print("Reference to d1 deleted.")
## The garbage collector may not run immediately.
## We add a small delay to give it time to run.
time.sleep(1)
print("\nScript is about to end. d2 will be deleted automatically.")
Save the file. Now, run the test_del.py script in the terminal.
python ~/project/test_del.py
Observe the output. The __del__ message for Tom appears after del d1 is called. The message for John appears at the very end, as the d2 object is garbage collected when the script finishes.
Creating two Dog objects: d1 and d2.
Deleting reference to d1...
The Dog object Tom is being deleted.
Reference to d1 deleted.
Script is about to end. d2 will be deleted automatically.
The Dog object John is being deleted.
Note: The exact timing of garbage collection can vary. __del__ is called when the object is collected, not necessarily immediately after del is used.