Python’s magic method __del__()
is called the finalizer method or, wrongly, the destructor method — the latter being wrong because it doesn’t actually destroy the object. Python calls __del__()
upon deletion of a given instance. For example, the expression del my_obj
will eventually initiate my_obj.__del__()
.
We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.
π‘ Note: the expression del my_obj
actually decrements the reference count for my_obj
. It doesnβt directly call my_obj.__del__()
because this method is only called when the reference count reaches zero.
Syntax and Example
object.__del__(self)
Let’s have a look at an example:
class MyClass: def __del__(self): print('hello world') my_obj = MyClass() del my_obj # hello world
References: