The __del__ method in python: destroy the object

The __del__() method in the function: Destroy the object
Python constructs an instantiated object of the current class by calling the __init__() method, and the __del__() method is used to destroy the instantiated object.
In fact, when writing a program, if the class instantiation object we created before is no longer used in the subsequent program, it is best to manually destroy it at a suitable location to release the memory space it takes up (the whole process is called garbage collection (abbreviation: GC) ).

In most cases, Python developers do not need to manually perform garbage collection, because Python has an automatic garbage collection mechanism that can destroy instance objects that do not need to be used.

Example one

# -*- coding:utf8 -*-class User:
def __init__(self):
print("=== 调用 __init__() 方法构造对象 ===")
def __del__(self):
print("调用__del__() 销毁对象,(对象占用的内存被回收)")
u1 = User()
print('#'*50)

operation result:

D:\pythonproject\venv\Scripts\python.exe D:/pythonproject/私有属性2.py
=== 调用 __init__() 方法构造对象 ===
##################################################
调用__del__() 销毁对象,(对象占用的内存被回收)
Process finished with exit code 0

Note: The above code will not call the __del__() method when running under interactive python programming, and it will not print out calling __del__() to destroy the object (the memory occupied by the object is recycled), because the program is not over.

Conclusion: Python will call the __del__() method before the end of the program to automatically destroy the object for us, and then release the memory occupied by the object. Pay attention to the location of the __del__() method call, after the print('#'*50) statement .

Example two

# -*- coding:utf8 -*-class User:
def __init__(self):
    print("=== 调用 __init__() 方法构造对象 ===")
def __del__(self):
    print("调用__del__() 销毁对象,(对象占用的内存被回收)")
u1 = User()
del u1
print('#'*50)

operation result:

D:\pythonproject\venv\Scripts\python.exe D:/pythonproject/私有属性2.py
=== 调用 __init__() 方法构造对象 ===
调用__del__() 销毁对象,(对象占用的内存被回收)
##################################################
Process finished with exit code 0

Conclusion: Manually delete the object, and then call the __del__() method to destroy the memory object and release the memory space.

Example three

# -*- coding:utf8 -*-class User:
def __init__(self):
print("=== 调用 __init__() 方法构造对象 ===")
def __del__(self):
print("调用__del__() 销毁对象,(对象占用的内存被回收)")
u1 = User()
u2 = u1# 
del u1 # 从运行结果可以看出来,执行该语句没有调用 __del__()方法,而是在程序即将运行结束的时候,程序自动调用了__del__()方法,销毁了对象
print('#'*50)# print('\n')# del u2# print("*"*50)

operation result:

D:\pythonproject\venv\Scripts\python.exe D:/pythonproject/销毁对象3.py
=== 调用 __init__() 方法构造对象 ===
##################################################
调用__del__() 销毁对象,(对象占用的内存被回收)

Process finished with exit code 0

Conclusion: It can be seen from the running results that the execution of the statement del u1 calls the __del__() method, but it is not executed immediately, but when the program is about to end, the program automatically calls the __del__() method, destroying the memory object , Here involves Python's garbage collection mechanism.
Python uses automatic reference counting (referred to as: ARC (auto-refrence-count)) to implement the garbage collection mechanism. The core idea of ​​this method is: each Python object will be configured with a counter, and the counter value of the initial Python instance object is 0. If there is a variable that references the instance object, the value of the counter will also increase by 1, and so on; When a variable dereferences the instance object, the counter will decrease by 1. If the counter value of a Python object is 0, it means that there is no variable referencing the Python object, which means that the program no longer needs it. At this time, Python will automatically call the __del__() method to recycle it.

Analysis of the third example above: In fact, the process of constructing the u1 instance object is divided into two steps. First, use User() to call the __init__() method in this class to construct an object of this class (we call it U, the counter is 0 ), and immediately use the variable u1 as a reference to the created instance object (the counter value of U + 1). On this basis, there is another u2 variable referencing u1 (actually equivalent to referencing User(), at this time the counter of U is +1). At this time, if you call the del u1 statement, it will only cause the counter of C to decrease by 1 (the value changes Is 1), so the counter value of C is not 0, so U will not be destroyed (the __del__() method will not be executed).

Example four

# -*- coding:utf8 -*-class User:
def __init__(self):
print("=== 调用 __init__() 方法构造对象 ===")
def __del__(self):
print("调用__del__() 销毁对象,(对象占用的内存被回收)")
u1 = User()
u2 = u1del u1 # 从运行结果可以看出来,执行该语句没有调用 __del__()方法,而是在程序即将运行结束的时候,程序自动调用了__del__()方法,销毁了对象print('#'*50)
# print('\n')# del u2print("*"*50)

operation result:

D:\pythonproject\venv\Scripts\python.exe D:/pythonproject/私有属性2.py
=== 调用 __init__() 方法构造对象 ===
##################################################
**************************************************
调用__del__() 销毁对象,(对象占用的内存被回收)
Process finished with exit code 0

Example 5:

# -*- coding:utf8 -*-class User:
def __init__(self):
print("=== 调用 __init__() 方法构造对象 ===")
def __del__(self):
print("调用__del__() 销毁对象,(对象占用的内存被回收)")
u1 = User()
u2 = u1del u1 # 从运行结果可以看出来,执行该语句没有调用 __del__()方法,而是在程序即将运行结束的时候,程序自动调用了__del__()方法,销毁了对象print('#'*50)
print('\n')
del u2print("*"*50)

operation result:

D:\pythonproject\venv\Scripts\python.exe D:/pythonproject/私有属性2.py
=== 调用 __init__() 方法构造对象 ===
##################################################
调用__del__() 销毁对象,(对象占用的内存被回收)
**************************************************
Process finished with exit code 0

By Four examples and five examples of comparison of two instances, we find that: instance of an object is referenced n times, the counter is n, then the reference counter referenced by this instance of an object to perform a del objects will automatically minus 1, When the counter of the instance object is reduced to zero, the __del__() method in the class will be called and executed. If the counter is not zero, the __del__() method in the instance object will not be executed, and then the program will end soon Previously, the python interpreter would automatically execute the __del__() method to destroy the object.

Guess you like

Origin blog.csdn.net/weixin_48505120/article/details/107586395