Here is a slightly opinionated answer.

Don't use __del__. This is not C++ or a language built for destructors. The __del__ method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del __, be aware of the basic limitations per http://docs.python.org/reference/datamodel.html:

  • __del__ is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you execution del object.
  • __del__ is responsible for calling any __del__ in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.
  • Having a __del__ means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored from gc.garbage. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see http://mail.python.org/pipermail/python-ideas/2009-October/006194.html.
  • The __del__ function can cheat, saving a reference to an object, and stopping the garbage collection.
  • Exceptions explicitly raised in __del__ are ignored.
  • __del__ complements __new__ far more than __init__. This gets confusing. See http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-1-del-is-not-the-opposite-of-init/ for an explanation and gotchas.
  • __del__ is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the __del__ on globals causes odd ordering issues, e.g., http://bugs.python.org/issue5099. Should __del__ called even if the __init__ fails? See http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423 for a long thread.

But, on the other hand:

  • __del__ means you do not forget to call a close statement. See http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/ for a pro __del__ viewpoint. This is usually about freeing ctypes or some other special resource.

And my pesonal reason for not liking the __del__ function.

  • Everytime someone brings up __del__ it devolves into thirty messages of confusion.
  • It breaks these items in the Zen of Python:
    • Complex is better than complicated.
    • Special cases aren't special enough to break the rules.
    • Errors should never pass silently.
    • In the face of ambiguity, refuse the temptation to guess.
    • There should be one-- and preferably only one --obvious way to do it.
    • If the implementation is hard to explain, it's a bad idea.

So, find a reason not to use __del__.

Answer from Charles Merriam on Stack Overflow
🌐
Medium
medium.com › @abhishekjainindore24 › demystifying-constructors-and-destructors-in-python-a-beginners-guide-b5bd6988f4bb
Demystifying Constructors and Destructors in Python: A Beginner’s Guide | by Abhishek Jain | Medium
February 5, 2024 - A constructor is a special method in a class that is automatically called when an object of that class is created. It is used to initialize the attributes of the object, providing a way to set up the object’s initial state.
🌐
Medium
medium.com › @explorarc.official › what-are-constructors-and-destructors-in-python-presented-by-explorarc-71db0cc1df47
What are Constructors and Destructors in Python — Presented By ExplorArc | by Explor Arc | Medium
July 22, 2023 - In Python, constructors and destructors are special methods that are automatically called when an object is created and destroyed, respectively. They provide a way to initialize object attributes and perform cleanup operations when an object ...
🌐
PREP INSTA
prepinsta.com › home › python tutorial › constructor & destructor in python
Constructor & Destructor in Python and their function | PrepInsta
June 16, 2023 - Constructor & Destructor in Python-constructors are used to initialize the object’s state and Destructors are used to destroying the object
🌐
Python
pythonprogramminglanguage.com › destructor
Destructor in a Python class - Python
In Python, destructors are designed to handle the destruction of objects, contrastingly to constructors that manage object creation. In Python, destructors and constructors are automatically executed, ensuring seamless object lifecycle management without manual intervention.
🌐
LinkedIn
linkedin.com › pulse › understanding-constructors-destructors-python-initializing-
Understanding Constructors and Destructors in Python: Initializing and Cleaning Up Objects
February 15, 2023 - Constructors And Destructors in Python In Python, a constructor is a special method that gets called when an object is created. It is used to initialize the object's attributes with default or given values.
🌐
Engineer\'s Portal
er.yuvayana.org › home › python › constructor and destructor in python
Constructor and Destructor in Python with examples
December 10, 2022 - This tutorial is about constructor and destructor in Python with examples. There are two type of constructor 1. default constructor 2. parameterized constructor
🌐
EyeHunts
tutorial.eyehunts.com › home › constructor and destructor in python | basics
Constructor and destructor in Python | Basics
August 29, 2022 - Python Constructor is the special function that is automatically executed when an object of a class is created. Python __init__ function is to act as a Constructor. ... Python Destructor is also a special method that gets executed automatically ...
Top answer
1 of 2
24

Here is a slightly opinionated answer.

Don't use __del__. This is not C++ or a language built for destructors. The __del__ method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del __, be aware of the basic limitations per http://docs.python.org/reference/datamodel.html:

  • __del__ is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you execution del object.
  • __del__ is responsible for calling any __del__ in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.
  • Having a __del__ means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored from gc.garbage. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see http://mail.python.org/pipermail/python-ideas/2009-October/006194.html.
  • The __del__ function can cheat, saving a reference to an object, and stopping the garbage collection.
  • Exceptions explicitly raised in __del__ are ignored.
  • __del__ complements __new__ far more than __init__. This gets confusing. See http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-1-del-is-not-the-opposite-of-init/ for an explanation and gotchas.
  • __del__ is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the __del__ on globals causes odd ordering issues, e.g., http://bugs.python.org/issue5099. Should __del__ called even if the __init__ fails? See http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423 for a long thread.

But, on the other hand:

  • __del__ means you do not forget to call a close statement. See http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/ for a pro __del__ viewpoint. This is usually about freeing ctypes or some other special resource.

And my pesonal reason for not liking the __del__ function.

  • Everytime someone brings up __del__ it devolves into thirty messages of confusion.
  • It breaks these items in the Zen of Python:
    • Complex is better than complicated.
    • Special cases aren't special enough to break the rules.
    • Errors should never pass silently.
    • In the face of ambiguity, refuse the temptation to guess.
    • There should be one-- and preferably only one --obvious way to do it.
    • If the implementation is hard to explain, it's a bad idea.

So, find a reason not to use __del__.

2 of 2
2

As I understood them from my early CPTS experiance:

Constructors: Constructors are mainly used in classes to initialze the class with values, and gives an oppurtunity to do some background work based on creation. If you pass in values during the creation of an object, this is where you can handle assignment of those values to variables within your class. (In this case, upon construction you are incrementing a variable that keeps track of population).

Destructors: Destructors cleanup a class. In python, due to the garbage collector it's not as important as languages that can leave hanging pointers (c++). (In this case you are decrementing the population variable on destruction of the object).

Find elsewhere
🌐
Uomus
uomus.edu.iq › img › lectures21 › MUCLecture_2023_11335913.pdf pdf
Constructor & Destructor in Python
Constructor & Destructor are an important concept of oops in Python . Constructor: A constructor in Python is a special type of method which is used to initialize the instance · members of the class. The task of constructors is to initialize and assign values to the data members of
🌐
Saralcode
saralcode.com › python › constructors-and-destructors-in-python
Constructors and Destructors in Python - OOP
Constructors are used to initialize an object when it is created, while destructors are used to clean up memory when an object is no longer needed. A constructor in Python is a special method with the name __init__. The __init__ method is called automatically when an object is created, and ...
🌐
Medium
medium.com › @divine_inner_voice › understanding-constructors-and-destructors-in-python-initializing-and-cleaning-up-objects-c32cdf3d32ba
Understanding Constructors and Destructors in Python: Initializing and Cleaning Up Objects
November 1, 2024 - They are defined with the __init__ method and are automatically called when an object is created. Constructors can also be used to set default values for attributes. Destructors are used to perform cleanup actions such as releasing resources, ...
🌐
GeeksforGeeks
geeksforgeeks.org › destructors-in-python
Destructors in Python - GeeksforGeeks
August 9, 2024 - Decorators are ... Constructors in PythonDestructors 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.
🌐
Shaalaa
shaalaa.com › question-bank-solutions › how-to-define-constructor-and-destructor-in-python-constructor-and-destructor-in-python_230559
How to define constructor and destructor in Python? - Computer Science | Shaalaa.com
July 1, 2021 - It is just opposite to the constructor. In Python, the _del_ () method is used as the destructor. ... class Example: def _init_ (self): print “Object created” # destructor def _del_ (self): print “Object destroyed” # creating an object myObj = Example () ... Q 5.Q 4.Q 1. Chapter 10: Python Classes and ...
🌐
BrainKart
brainkart.com › article › Constructor-and-Destructor-in-Python_37275
Constructor and Destructor in Python
December 13, 2018 - It is initialized to zero and each ... Destructor is also a special method gets executed automatically when an object exit from the scope. It is just opposite to constructor. In Python, __del__( ) method is used as destructor....
🌐
Analytics Vidhya
analyticsvidhya.com › home › what is a destructor in python? uses, code implementation and more
What is a Destructor in Python? Uses, Code Implementation and More
February 15, 2024 - The key differences between constructors and destructors are: Purpose: Constructors initialize objects, while destructors clean them up. Invocation: Constructors are called when an object is created, whereas destructors are called when an object ...
🌐
Scaler
scaler.com › home › topics › what is destructor in python?
Destructor In Python - Scaler Topics
May 4, 2023 - Constructor is automatically called when an object is created, whereas destructor is called when an object is destroyed. ... __del __() Method: In Python, the __del __() is referred to as a destructor method.
🌐
Slideshare
slideshare.net › home › education › chapter 06 constructors and destructors
Chapter 06 constructors and destructors | PPTX
Constructors and destructors in Python. Constructors are special methods that are called automatically when an object is created. They initialize variables and ensure objects are properly initialized.
🌐
Javatpoint
javatpoint.com › destructors-in-python
Destructors in Python - Javatpoint
Destructors in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, operators, etc.
🌐
Studytonight
studytonight.com › python › destructors-in-python
Python Destructors | Studytonight
class Foo(): def __init__(self, id, bar): self.id = id; # saving reference of Bar object self.friend = bar; print ('Foo', self.id, 'born'); def __del__(self): (print 'Foo', self.id, 'died'); class Bar(): def __init__(self, id): self.id = id; # saving Foo class object in variable # 'friend' of Bar class, and sending # reference of Bar object for Foo object # initialisation self.friend = Foo(id, self); print ('Bar', self.id, 'born') def __del__(self): print ('Bar', self.id, 'died') b = Bar(12) ... In object oriented progamming, destructor is only called in case an object is successfully created, because if the any exception occurs in the constructor then the constructor itself destroys the object. But in python, if any exception occurs in the __init__ method while initialising the object, in that case too, the method __del__ gets called.