Open In App

Destructors in Python

Last Updated : 13 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Constructors in Python
Destructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. 
The __del__() method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected. 
Syntax of destructor declaration : 
 

def __del__(self):
  # body of destructor

Note : A reference to objects is also deleted when the object goes out of reference or when the program ends. 
Example 1 : Here is the simple example of destructor. By using del keyword we deleted the all references of object ‘obj’, therefore destructor invoked automatically.
 

Python3




# Python program to illustrate destructor
class Employee:
 
    # Initializing
    def __init__(self):
        print('Employee created.')
 
    # Deleting (Calling destructor)
    def __del__(self):
        print('Destructor called, Employee deleted.')
 
obj = Employee()
del obj


Output

Employee created.
Destructor called, Employee deleted.

Note : The destructor was called after the program ended or when all the references to object are deleted i.e when the reference count becomes zero, not when object went out of scope.
Example 2: This example gives the explanation of above-mentioned note. Here, notice that the destructor is called after the ‘Program End…’ printed.

Python3




# Python program to illustrate destructor
  
class Employee:
  
    # Initializing
    def __init__(self):
        print('Employee created')
  
    # Calling destructor
    def __del__(self):
        print("Destructor called")
  
def Create_obj():
    print('Making Object...')
    obj = Employee()
    print('function end...')
    return obj
  
print('Calling Create_obj() function...')
obj = Create_obj()
print('Program End...')


Output

Calling Create_obj() function...
Making Object...
Employee created
function end...
Program End...
Destructor called

Example 3: Now, consider the following example :  

Python3




# Python program to illustrate destructor
  
class A:
    def __init__(self, bb):
        self.b = bb
  
class B:
    def __init__(self):
        self.a = A(self)
    def __del__(self):
        print("die")
  
def fun():
    b = B()
  
fun()


Output

die

In this example when the function fun() is called, it creates an instance of class B which passes itself to class A, which then sets a reference to class B and resulting in a circular reference.
Generally, Python’s garbage collector which is used to detect these types of cyclic references would remove it but in this example the use of custom destructor marks this item as “uncollectable”. 
Simply, it doesn’t know the order in which to destroy the objects, so it leaves them. Therefore, if your instances are involved in circular references they will live in memory for as long as the application run.

NOTE : The problem mentioned in example 3 is resolved in newer versions of python, but it still exists in version < 3.4 .

Example: Destruction in recursion

In Python, you can define a destructor for a class using the __del__() method. This method is called automatically when the object is about to be destroyed by the garbage collector. Here’s an example of how to use a destructor in a recursive function:

Python




class RecursiveFunction:
    def __init__(self, n):
        self.n = n
        print("Recursive function initialized with n =", n)
 
    def run(self, n=None):
        if n is None:
            n = self.n
        if n <= 0:
            return
        print("Running recursive function with n =", n)
        self.run(n-1)
 
    def __del__(self):
        print("Recursive function object destroyed")
 
# Create an object of the class
obj = RecursiveFunction(5)
 
# Call the recursive function
obj.run()
 
# Destroy the object
del obj


Output

('Recursive function initialized with n =', 5)
('Running recursive function with n =', 5)
('Running recursive function with n =', 4)
('Running recursive function with n =', 3)
('Running recursive function with n =', 2)
('Running recursive function with n =', 1)
Recursive function object destroyed

In this example, we define a class RecursiveFunction with an __init__() method that takes in a parameter n. This parameter is stored as an attribute of the object.

We also define a run() method that takes in an optional parameter n. If n is not provided, it defaults to the value of self.n. The run() method runs a recursive function that prints a message to the console and calls itself with n-1.

We define a destructor using the __del__() method, which simply prints a message to the console indicating that the object has been destroyed.

We create an object of the class RecursiveFunction with n set to 5, and call the run() method. This runs the recursive function, printing a message to the console for each call.

Finally, we destroy the object using the del statement. This triggers the destructor, which prints a message to the console indicating that the object has been destroyed.

Note that in this example, the recursive function will continue running until n reaches 0. When n is 0, the function will return and the object will be destroyed by the garbage collector. The destructor will then be called automatically.

Advantages of using destructors in Python:

  • Automatic cleanup: Destructors provide automatic cleanup of resources used by an object when it is no longer needed. This can be especially useful in cases where resources are limited, or where failure to clean up can lead to memory leaks or other issues.
  • Consistent behavior: Destructors ensure that an object is properly cleaned up, regardless of how it is used or when it is destroyed. This helps to ensure consistent behavior and can help to prevent bugs and other issues.
  • Easy to use: Destructors are easy to implement in Python, and can be defined using the __del__() method.
  • Supports object-oriented programming: Destructors are an important feature of object-oriented programming, and can be used to enforce encapsulation and other principles of object-oriented design.
  • Helps with debugging: Destructors can be useful for debugging, as they can be used to trace the lifecycle of an object and determine when it is being destroyed.

Overall, destructors are an important feature of Python and can help to ensure that objects are properly cleaned up and resources are not wasted. They are easy to use and can be useful for enforcing encapsulation and other principles of object-oriented design.



Previous Article
Next Article

Similar Reads

Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Visualizing O(n) using Python
Introduction Algorithm complexity can be a difficult concept to grasp, even presented with compelling mathematical arguments. This article presents a tiny Python program that shows the relative complexity of several typical functions. It can be easily adapted to other functions. Complexity. Why it matters? Computational complexity is a venerable su
3 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Python | Convert list to Python array
Sometimes while working in Python we can have a problem in which we need to restrict the data elements to just one type. A list can be heterogeneous, can have data of multiple data types and it is sometimes undesirable. There is a need to convert this to a data structure that restricts the type of data. Convert List to Array PythonBelow are the met
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg