Mastering Objectoriented Python
上QQ阅读APP看书,第一时间看更新

The __del__() and close() methods

The most common use for __del__() is to ensure files are closed.

Generally, class definitions that open files will have something like what's shown in the following code:

__del__ = close

This will ensure the __del__() method is also the close() method.

Anything more complex than this is better done with a context manager. See Chapter 5, Using Callables and Contexts, for more information on context managers.