Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
destructor
communitycreator

What is a destructor in Python?

Maria Elijah

A destructor method is called when all references to an object have been destroyed. In Python, the __del__() method is referred to as a destructor method.

Destructors aren’t as important in Python as they are in C++, because Python contains a garbage collector that takes care of memory management automatically.

Syntax

def __del__(self):
  # body of destructor

When an object is no longer referenced or the program finishes, a reference to it is likewise erased.

Code

The following code shows how to use the __del__() function and the del keyword to delete all of the object’s references, triggering the destructor to execute automatically.



class Student:
  
    # Initializing class named Student
    def __init__(self):
        print('The class named Student was created.')
  
    # Calling destructor
    def __del__(self):
        print('The destructor is called. Student is deleted.')
  
sObj = Student() 
del sObj

Explanation

In the code, the destructor was executed after the references to the object were destroyed or the program terminated.

Example 2

The following code shows when a destructor is invoked:

class Student:
  
   # Initializing class named Student
    def __init__(self):
        print('The class named Student was created.')
  
    # Calling destructor
    def __del__(self):
        print('The destructor is called. Student is deleted.')

def Create_obj():
    print('*** Creating Object ***')
    s_Object = Student()
    print('***End of Function***')
    return s_Object
  
print('***Calling Create_obj()***')
myObj = Create_obj()
print('***Program Ends***')

RELATED TAGS

python
destructor
communitycreator
RELATED COURSES

View all Courses

Keep Exploring