The __del__ method works in the Python object

  • 2021-01-18 06:35:13
  • OfStack

__del__ is a method that takes effect when the object is erased by gc, and its execution usually means that the object cannot be referenced again.

The sample code is as follows:


class Demo:

def __del__(self):

  print("calling __del__")
 
obj = Demo()

del obj

The program execution results are as follows:


grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python del_method.py

calling __del__

However, this is not the only way to make __del__ execute. In fact, this method can also be called directly. The test code is as follows:


class Demo:

def __init__(self):

  print("calling __del__")

obj = Demo()

obj.__del__()

Program execution result:


grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python del_method.py

calling __del__ 

However, many times such an execution does not guarantee the proper execution of garbage collection.

The following code:


grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python del_method.py

calling __del__

calling __del__

Execution Result:


grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python del_method.py

calling __del__

calling __del__

Speculation: The above deletion method triggered two deletes, but due to reference, deletion destruction was not actually implemented.

Modify the code to verify as follows:


class Demo:

def __del__(self):

  print("calling __del__")

  del self

 

obj = Demo()

obj.__del__()

print(id(obj))

Execution Result:


grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python del_method.py

calling __del__

140726800222040

calling __del__

From the above, the main object is the reference, the destruction of the object is not completed until the object reference is no longer. Step 1 Verify the code:


class Demo:

def __del__(self):

  print("calling __del__")

  del self

 

obj = Demo()

obj.__del__()

print(id(obj))

print(id(obj))

Execution Result:


grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python del_method.py

calling __del__

140568015406936

140568015406936

calling __del__

Judging from the above results, the guess is accurate.


Related articles: