- Mastering Objectoriented Python
- Steven F. Lott
- 72字
- 2021-11-12 16:25:09
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.