Entri Blog
No Result
View All Result
Friday, January 27, 2023
  • State Level PSC
    • Kerala PSC
    • TNPSC
    • APPSC
    • TSPSC
    • BPSC
    • Karnataka PSC
    • MPPSC
    • UPPSC
  • Banking
  • SSC
  • Railway
  • Entri Skilling
    • Coding
    • Spoken English
    • Stock Marketing
  • TET
    • APTET
    • CTET
    • DSSSB
    • Karnataka TET
    • Kerala TET
    • KVS
    • MPTET
    • SUPER TET
    • TNTET
    • TSTET
    • UPTET
FREE GK TEST: SIGNUP NOW
Entri Blog
  • State Level PSC
    • Kerala PSC
    • TNPSC
    • APPSC
    • TSPSC
    • BPSC
    • Karnataka PSC
    • MPPSC
    • UPPSC
  • Banking
  • SSC
  • Railway
  • Entri Skilling
    • Coding
    • Spoken English
    • Stock Marketing
  • TET
    • APTET
    • CTET
    • DSSSB
    • Karnataka TET
    • Kerala TET
    • KVS
    • MPTET
    • SUPER TET
    • TNTET
    • TSTET
    • UPTET
No Result
View All Result
Entri Blog
Free GK Test
banner top article banner top article
Home Articles

Complete Understanding of Destructors in Python

by Feeba Mahin
November 19, 2022
in Articles
Complete Understanding of Destructors in Python
Share on FacebookShare on WhatsAppShare on Telegram

Table of Contents

  • Destructor is a special method that is called when an object gets destroyed. On the other hand, a constructor is used to create and initialize an object of a class.
  • What is Destructor in Python?
  • Create Destructor using the __del__() Method
  • Important Points to Remember about Destructor
  • Cases when Destructor doesn’t work Correctly
  • Conclusion

Destructor is a special method that is called when an object gets destroyed. On the other hand, a constructor is used to create and initialize an object of a class.

After reading this article, you will learn:

  • How create a destructor in Python
  • The use of __del__() method
  • Wokring of a destructor

Python and Machine Learning Square

What is Destructor in Python?

In object-oriented programming, A destructor is called when an object is deleted or destroyed. Destructor is used to perform the clean-up activity before destroying the object, such as closing database connections or filehandle.

Python has a garbage collector that handles memory management automatically. For example, it cleans up the memory when an object goes out of scope.

But it’s not just memory that has to be freed when an object is destroyed. We must release or close the other resources object were using, such as open files, database connections, cleaning up the buffer or cache. To perform all those cleanup tasks we use destructor in Python.

The destructor is the reverse of the constructor. The constructor is used to initialize objects, while the destructor is used to delete or destroy the object that releases the resource occupied by the object.

In Python, destructor is not called manually but completely automatic. destructor gets called in the following two cases

  • When an object goes out of scope or
  • The reference counter of the object reaches 0.

Learn Coding from Experts!

In Python, The special method __del__() is used to define a destructor. For example, when we execute del object_name destructor gets called automatically and the object gets garbage collected.

Python destructor to destroy an object
Python destructor to destroy an object

Create Destructor using the __del__() Method

The magic method __del__() is used as the destructor in Python. The __del__() method will be implicitly invoked when all references to the object have been deleted, i.e., is when an object is eligible for the garbage collector.

This method is automatically called by Python when the instance is about to be destroyed. It is also called a finalizer or (improperly) a destructor.

Syntax of destructor declaration

def __del__(self):
    # body of a destructor

Where,

  • def: The keyword is used to define a method.
  • __del__() Method: It is a reserved method. This method gets called as soon as all references to the object have been deleted
  • self: The first argument self refers to the current object.

Note: The __del__() method arguments are optional. We can define a destructor with any number of arguments.

Example

Let’s see how to create a destructor in Python with a simple example. In this example, we’ll create a Class Student with a destructor. We’ll see: –

  • How to implement a destructor
  • how destructor gets executed when we delete the object.
class Student:

    # constructor
    def __init__(self, name):
        print('Inside Constructor')
        self.name = name
        print('Object initialized')

    def show(self):
        print('Hello, my name is', self.name)

    # destructor
    def __del__(self):
        print('Inside destructor')
        print('Object destroyed')

# create object
s1 = Student('Emma')
s1.show()

# delete object
del s1

Output

Inside Constructor
Object initialized

Hello, my name is Emma

Inside destructor
Object destroyed

Note:

As you can see in the output, the __del__() method get called automatically is called when we deleted the object reference using del s1.

In the above code, we created one object. The s1 is the reference variable that is pointing to the newly created object.

The destructor has called when the reference to the object is deleted or the reference count for the object becomes zero

Grab the opportunity to learn Python with Entri! Click Here

Important Points to Remember about Destructor

  • The __del__ method is called for any object when the reference count for that object becomes zero.
  • The reference count for that object becomes zero when the application ends, or we delete all references manually using the del keyword.
  • The destructor will not invoke when we delete object reference. It will only invoke when all references to the objects get deleted.
Working of destructor
Working of destructor

Example:

Let’s understand the above points using the example.

  • First create object of a student class using s1 = student('Emma')
  • Next, create a new object reference s2 by assigning s1 to s2 using s2=s1
  • Now, both reference variables s1 and s2 point to the same object.
  • Next, we deleted reference s1
  • Next, we have added 5 seconds of sleep to the main thread to understand that destructors only invoke when all references to the objects get deleted.
import time

class Student:

    # constructor
    def __init__(self, name):
        print('Inside Constructor')
        self.name = name

    def show(self):
        print('Hello, my name is', self.name)

    # destructor
    def __del__(self):
        print('Object destroyed')

# create object
s1 = Student('Emma')
# create new reference
# both reference points to the same object
s2 = s1
s1.show()

# delete object reference s1
del s1

# add sleep and observe the output
time.sleep(5)
print('After sleep')
s2.show()

Output:

Inside Constructor
Hello, my name is Emma

After Sleep

After sleep
Hello, my name is Emma
Object destroyed
  • As you can see in the output destructors only invoked when all references to the objects get deleted.
  • Also, the destructor is executed when the code (application) ends and the object is available for the garbage collector. (I.e., we didn’t delete object reference s2 manually using del s2).

Cases when Destructor doesn’t work Correctly

The __del__ is not a perfect solution to clean up a Python object when it is no longer required. In Python, the destructor behave behaves weirdly and doesn’t execute in the following two cases.

  1. Circular referencing when two objects refer to each other
  2. Exception occured in __init__() method

Grab the opportunity to learn Python with Entri! Click Here

Circular Referencing

The __del()__() doesn’t work correctly in the case of circular referencing. In circular referencing occurs when two objects refer to each other.

When both objects go out of scope, Python doesn’t know which object to destroy first. So, to avoid any errors, it doesn’t destroy any of them.

In short, it means that the garbage collector does not know the order in which the object should be destroyed, so it doesn’t delete them from memory.

Ideally, the destructor must execute when an object goes out of scope, or its reference count reaches zero.

But the objects involved in this circular reference will remain stored in the memory as long as the application will run.

Example:

In the below example, ideally, both Vehicle and Car objects must be destroyed by the garbage collector after they go out of scope. Still, because of the circular reference, they remain in memory.

I’d recommend using Python’s with statement for managing resources that need to be cleaned up.

import time


class Vehicle():
    def __init__(self, id, car):
        self.id = id;
        # saving reference of Car object
        self.dealer = car;
        print('Vehicle', self.id, 'created');

    def __del__(self):
        print('Vehicle', self.id, 'destroyed');


class Car():
    def __init__(self, id):
        self.id = id;
        # saving Vehicle class object in 'dealer' variable
        # Sending reference of Car object ('self') for Vehicle object
        self.dealer = Vehicle(id, self);
        print('Car', self.id, 'created')

    def __del__(self):
        print('Car', self.id, 'destroyed')


# create car object
c = Car(12)
# delete car object
del c
# ideally destructor must execute now

# to observe the behavior
time.sleep(8)

Output:

Vehicle 12 created
Car 12 created

Exception in __init__ Method

In object-oriented programming, A constructor is a special method used to create and initialize an object of a class. using the __init__() method we can implement a constructor to initialize the object.

In OOP, if any exception occurs in the constructor while initializing the object, the constructor destroys the object.

Likewise, in Python, if any exception occurs in the init method while initializing the object, the method del gets called. But actually, an object is not created successfully, and resources are not allocated to it

even though the object was never initialized correctly, the del method will try to empty all the resources and, in turn, may lead to another exception.

Example:

class Vehicle:
    def __init__(self, speed):
        if speed > 240:
            raise Exception('Not Allowed');
        self.speed = speed;

    def __del__(self):
        print('Release resources')

# creating an object
car = Vehicle(350);
# to delete the object explicitly
del car

Output:

Traceback (most recent call last):
Release resources
Exception: Not Allowed

Conclusion

  • In object-oriented programming, A destructor is called when an object is deleted or destroyed.
  • Destructor is used to perform the clean-up activity before destroying the object, such as closing database connections or filehandle.
  • In Python we use __del__() method to perform clean-up task before deleting the object.
  • The destructor will not invoke when we delete object reference. It will only invoke when all references to the objects get deleted.

Python and Machine Learning Square

Share61SendShare
Feeba Mahin

Feeba Mahin

Related Posts

Kerala PSC Junior Public Health Nurse Gr. II Rank List 2022 Out - PDF, Direct Link
Articles

Kerala PSC Junior Public Health Nurse Gr. II Rank List 2022 Out – PDF, Direct Link

January 25, 2023
HPSC HCS Personality Test 2021- 22 Date Out - Check Schedule
Articles

HPSC HCS Personality Test 2021- 22 Date Out – Check Schedule

January 25, 2023
GPSC Engineering Service Answer Key 2023 PDF - Link, Raise Objection
Articles

GPSC Engineering Service Answer Key 2023 PDF – Link, Raise Objection

January 25, 2023
Next Post
World Television Day 2022 - History, Significance, Quiz

World Television Day 2022 - History, Significance, Quiz

Discussion about this post

Latest Posts

  • Kerala PSC Junior Public Health Nurse Gr. II Rank List 2022 Out – PDF, Direct Link
  • HPSC HCS Personality Test 2021- 22 Date Out – Check Schedule
  • GPSC Engineering Service Answer Key 2023 PDF – Link, Raise Objection
  • Kerala PSC Exam Calendar April 2023 – Download PDF Here, Link
  •  8 Interview Skills To Ace Your Next Interview

Trending Posts

  • states of india and their capitals and languages

    List of 28 States of India and their Capitals and Languages 2023 – PDF Download

    149714 shares
    Share 59883 Tweet 37427
  • List of Government Banks in India 2023: All you need to know

    60986 shares
    Share 24394 Tweet 15247
  • TNPSC Group 2 Posts and Salary Details 2022

    39409 shares
    Share 15764 Tweet 9852
  • New Map of India with States and Capitals 2022

    28551 shares
    Share 11420 Tweet 7138
  • Odisha Police Recruitment 2023 PDF Download for 4790 Posts – Eligibility, Selection Process

    833 shares
    Share 333 Tweet 208

Company

  • Become a teacher
  • Login to Entri Web

Quick Links

  • Articles
  • Videos
  • Entri Daily Quiz Practice
  • Current Affairs & GK
  • News Capsule – eBook
  • Preparation Tips
  • Kerala PSC Gold
  • Entri Skilling

Popular Exam

  • IBPS Exam
  • SBI Exam
  • Railway RRB Exam
  • Kerala PSC
  • Tamil Nadu PSC
  • Telangana PSC
  • Andhra Pradesh PSC
  • MPPSC
  • UPPSC
  • Karnataka PSC
  • Staff Selection Commission Exam

© 2021 Entri.app - Privacy Policy | Terms of Service

No Result
View All Result
  • State Level PSC
    • Kerala PSC
    • TNPSC
    • APPSC
    • TSPSC
    • BPSC
    • Karnataka PSC
    • MPPSC
    • UPPSC
  • Banking
  • SSC
  • Railway
  • Entri Skilling
    • Coding
    • Spoken English
    • Stock Marketing
  • TET
    • APTET
    • CTET
    • DSSSB
    • Karnataka TET
    • Kerala TET
    • KVS
    • MPTET
    • SUPER TET
    • TNTET
    • TSTET
    • UPTET

© 2021 Entri.app - Privacy Policy | Terms of Service