Can someone explain what I've done wrong...

Tim Roberts timr at probo.com
Tue Sep 20 02:18:16 EDT 2005


Jason <jason at jasonmhirst.co.uk> wrote:
>
>Have to say, I was confused with the post (I received via email,

Want to have even more fun?  Rename the variable "Sophie" to "Mophie", and
your script will work just as you expect.

>can't 
>see it on the newsgroup yet) from Astan Chee saying he couldn't 
>understand how the Person class was destroyed.  I'm still new(ish) with 
>Python but I was lead to believe the __del__ call was pretty reliable. 
>Thanks for the heads up on that.

Well, __del__ is reliable enough, but what's happening to you is more
complicated.

A class is an object, just as an instance of a class is an object.  When
you declare "class Person", that creates a class object, and binds it to
the name "Person" within your module.  When you say:

  Jason = Person("Jason")

that is calling a method function in the object bound to the "Person" name,
takes its return value, and binds it to the name "Jason".  Same thing
happens when you call Person() again and bind the result to the name
"Sophie".

Everything works OK while your script runs.  When the script exits, your
"main" module goes to clean things up.  Apparently, it does so
alphabetically.  First, it cleans up the name "Jason", which calls
Jason.__del__.  That works fine.  It then binds the name Jason to None.

Next, it cleans up the name "Person".  It does whatever __del__ does for
class objects.  It then binds the name "Person" to None.

Next, it cleans up the name "Sophie".  It calls __del__, which works.
However, when you try to access People, that name is now bound to None,
because it has already been cleaned up.

Kaboom.
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list