Linux/Unix > Python Essential Reference, Second Edition > 7. Classes and Object-Oriented Programming > Reference Counting and Instance Destruction | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105086039027214181029120

### 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 `close()` that a program can use to explicitly perform a shutdown. Finally, note that instances for which `_ _del_ _()` is defined cannot be collected by Python’s cyclic garbage collector (which is a strong reason not to define `_ _del_ _` unless you need it). See Appendix A, “The Python Library,” gc `gc` module for details.

Occasionally, a program will use the `del` statement to delete a reference to an object. If this causes the reference count of the object to reach zero, the `_ _del_ _()` method is called. However, in general, the `del` statement doesn’t directly call `_ _del_ _()`.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.