Categories: python

Destructors in Python

  • 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
Output:
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...')
Output:
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

Output:

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

Output:

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.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago