Destructors in Python

  • December 12, 2022
  • python
JOIN Clause
  • When an object is destroyed, the destructors are called. Destructors are not as necessary in Python as they are in C++ because Python has a garbage collector that manages memory automatically.
  • The _del_() method in Python is known as a destructor method.
  • When an object is garbage collected, or when all references to the object have been deleted, the function t is called.
  • Note : A reference to objects is also deleted when the object goes out of reference or when the program ends. 

Syntax of destructor declaration : 

def __del__(self):
  # body of destructor
Example : using _del_ method
# Python program to illustrate destructor
class Student:

	# Initializing
	def __init__(self):
		print('Student created.')

	# Deleting (Calling destructor)
	def __del__(self):
		print('Destructor called, Student deleted.')

obj = Student()
del obj
Student created.
Destructor called, Student deleted.

Here, the destructor was not called when the object was no longer in scope, but rather when the program terminated or when all references to the object were removed, or when the reference count was zero.

Example 2:
# Python program to illustrate destructor

class Student:

	# Initializing
	def __init__(self):
		print('Student created')

	# Calling destructor
	def __del__(self):
		print("Destructor called")

def Create_obj():
	print('Object creation')
	obj = Student()
	print('ending function')
	return obj

print('Calling Create_obj() function...')
obj = Create_obj()
print('Program End...')
Calling Create_obj() function...
Object creation
Student created
ending function
Program End...
Destructor called
Points to Remember about Destructor:
  • When an object’s reference count reaches zero, the del method is invoked for that object.
  • When the application closes, or we manually remove all references using the del keyword, the reference count for that object drops to zero.
  • When we delete an object reference, the destructor won’t be called. It won’t run until all references to the objects are removed.
Corner cases:

The destroyer occasionally fails to function properly. Let’s examine those scenarios.

1. Circular Referencing

A circular reference is a cyclic dependency in Python. Python’s garbage collector runs automatically when a program exits. It will try to free unused objects by removing them from the program’s memory. If you have a circular reference, the garbage collector will run infinitely until your program eventually crashes. For instance,

class A:
    def __init__(self):
        print("Object A Created")
    def __del__(self):
        print("Object A Destroyed")
class B:
    def __init__(self):
        print("Object B Created")
    def __del__(self):
        print("Object B Destroyed")

#creating two objects
a = A()
b = B()

#setting up circular reference
a.b = b
b.a = a

#deleting objects
del a
del b


Object A Created
Object B Created
2. Exception in __init__ method

Destructors are only called in object-oriented programming when an object is successfully created because, in the event of an exception in the constructor, the constructor itself destroys the object.

However, in Python, the method del is called in the event that an exception occurs while initializing the object in the init method.

The del method will therefore attempt to empty all the resources and variables even though the object was never initialized correctly, which could result in another exception. For instance,

class Example():
	def __init__(self, x):
	    # for x = 0, raise exception
		if x == 0:
			raise Exception();
		self.x = x;
	def __del__(self):
		print (self.x)

# creating an object
myObj = Example();
# to delete the object explicitly
del myObj


Exception ignored in: <function Example.__del__ at 0x7f0118581e50>
Traceback (most recent call last):
  File "<string>", line 9, in __del__
AttributeError: 'Example' object has no attribute 'x'
Traceback (most recent call last):
  File "<string>", line 12, in <module>
TypeError: __init__() missing 1 required positional argument: 'x'

Note: also read about Constructor in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

Leave a Reply

Your email address will not be published. Required fields are marked *