Reference Counting and Instance Destruction

All instances have a reference count. If the reference count reaches zero, the instance is destroyed. When the instance is about to be destroyed, the interpreter looks for a _ _del_ _() method associated with the object and calls it. In practice, it’s rarely necessary for a class to define a _ _del_ _() method. The only exception is when the destruction of an object requires a cleanup action such as closing a file, shutting down a network connection, or releasing other system resources. Even in these cases, it’s dangerous to rely on _ _del_ _() for a clean shutdown, as there’s no guarantee that this method will be called when the interpreter exits. A better approach may be to define a method such as ...

Get Python Essential Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.