如何以可靠的方式使用__del__? [英] How to use __del__ in a reliable way?
问题描述
我了解到python 可以 保证,只要删除对象,就会调用__del__
.
换句话说,del x
不一定必然调用它的析构函数x.__del__()
.
I have learned that python does not guarantee that __del__
is called whenever an object is deleted.
In other words, del x
does not necessarily invoke its destructor x.__del__()
.
If I want to ensure proper object cleanup, I should use a context manager (in a with
statement).
我知道它很愚蠢,但是出于两个原因(请不要问为什么),我被绑定到使用Python 2.4的系统上.因此上下文管理器毫无疑问(它们是在Python 2.5中引入的)
I know it's stupid, but for a couple of reasons (please don't ask why) I am tied to a system with Python 2.4; therefore context managers are out of question (they were introduced in Python 2.5)
因此,我需要一个替代解决方案,因此,我的问题是:是否有最佳实践可以帮助我可靠地使用__del__
?我在朝着的方向思考:如果python提供了这样的功能,那么肯定有一种可以有效使用它的方式(我只是很愚蠢地想出方法)" ,,
So I need a an alternative solution, and hence my question: are there best practices that would help me to use __del__
reliably? I am thinking in the direction of "if python provides such functionality, there must be a way it can be efficiently used (I'm just to stupid to figure out how)",,,
或者我只是天真,应该忘掉__del__
并转而使用一种完全不同的方法吗?
Or I am just being naive, should forget about __del__
and move on to a completely different approach?
推荐答案
简而言之:不,没有办法确保它被调用.
In short: No, there is no way to ensure it gets called.
答案是自己实施上下文管理器. with
语句大致翻译为:
The answer is to implement context managers yourself. A with
statement roughly translates to:
x.__enter__()
try:
...
finally:
x.__exit__()
因此,只需手动进行即可.它要复杂得多,所以我建议阅读 PEP 343 来阅读充分了解上下文管理器的工作原理.
So just do it manually. It is a little more complex than that, so I recommend reading PEP 343 to fully understand how context managers work.
一种选择是调用清理函数close()
,然后在将来的python版本中,人们可以轻松使用
One option is to call your cleaning up function close()
, and then in future versions of python, people can easily use contextlib.closing
to turn it into a real context manager.
这篇关于如何以可靠的方式使用__del__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!