[Tutor] destroying classes

dman dsh8290@rit.edu
Sun, 2 Dec 2001 17:25:30 -0500


On Sun, Dec 02, 2001 at 04:18:27PM -0600, Rob McGee wrote:

| Anyway, one of my classes has a method which should result in the
| destruction of the class instance.

You can't do this.

| But the method also wants to return a value. If I put a "del self"
| command in there, would the method end at that point, or would it
| continue to completion?

The only effect 'del self' would have is to remove the name "self"
from the local scope (now you have no way to access the instance any
more) and decrement its ref count by 1.  Everything else continues as
usual, and the client still has a reference to the instance so it
doesn't go away.

If you were using C++ you could do this ("delete this ;") but then the
client would have a dangling pointer that would at best give a
segmentation fault later, or at worst just cause weird data corruption
and behavior.

The reason you can't destroy an object is an object should only be
destroyed when it is impossible to use it anymore (that is, there are
no more references to it).  As hinted above, C++ makes you, the
prorgrammer, keep track and decide when the object should go away.
Python is the opposite - it keeps track for you and destroys the
object when you no longer have any references to it.

HTH,
-D

-- 

Contrary to popular belief, Unix is user friendly.
It just happens to be selective about who it makes friends with.
                                               -- Dave Parnas