__del__退出行为 [英] __del__ on exit behavior
问题描述
我有一些test.py文件:
I have some test.py file:
class A:
def __init__(self):
print("A init")
def __del__(self):
print("A del")
a = A()
当我运行10次时( python3 test.py
)它总是产生下一个输出:
When I run it 10 times (python3 test.py
) it always produces next output:
A init
A del
但是如果我在脚本末尾添加 sys.exit
调用:
But if I add sys.exit
call to end of script:
import sys
class A:
def __init__(self):
print("A init")
def __del__(self):
print("A del")
a = A()
sys.exit(-1)
在10例中有5例(随机)我有
in 5 of 10 cases (randomly) i have
A init
一半的情况:
A init
A del
我在Windows 7 x64上使用Python3.4.3 [MSC v.1600 32 bit]。
那么为什么不每次都调用 __ del __
方法呢?我是否需要使用其他退出方法来传递脚本的返回代码,并确保所有析构函数都已执行?还有一个相关的问题:是否可以在从OS接收SIGTERM或SIGKILL时执行析构函数?
I use Python3.4.3 [MSC v.1600 32 bit] on Windows 7 x64.
So why __del__
method called not every time? Do I need to use some other exit method to pass return code of script and have all destructors guaranteed executed? And one more related question: is it possible to execute destructors on receive SIGTERM or SIGKILL from OS?
推荐答案
从文档:
不能保证在解释器退出时仍对存在的对象调用
__ del __()
方法。
如果要确保调用 a .__ del __
,则必须明确删除实例:
If you want to ensure that a.__del__
is invoked, you'll have to explicitly delete the instance:
a = A()
del a # Assuming this is the final reference to the object
这篇关于__del__退出行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!