[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Re: Please explain what I've done wrong.



Jason schrieb:
> I also want to apologise if this isn't the write newsgroup to post on,
> but it's the only one I know of.  IF anyone knows a good newsgroup, I'd
> appreciate it.

Hi, the right group for this would probably be:

Tutor maillist  -  Tutor@xxxxxxxxxx
http://mail.python.org/mailman/listinfo/tutor

> [...]
> Sophie says bye.
> Exception exceptions.AttributeError: "'NoneType' object has no attribute
> 'popula
> tion'" in <bound method Person.__del__ of <__main__.Person instance at
> 0x0097B53
> 0>> ignored
> 
> I've looked through the code but can't find anything obvious.

I tried this myself and also get this error. I changed the __del__() method to
the following:

    def __del__(self):
        print "%s says bye." % self.name

        person = self.__class__

        person.population -= 1

        if person.population == 0:
            print "I am the last one"
        else:
            print "There are still %d people left." % person.population

and this works as you expected.

Why is this so?

As you probably know, the __del__ method is called, when a object is deleted.
This happens also, when the object is no longer referenced by anything and the
Python garbage collector deletes the object.

You relied on the fact here, that Python does all the necessary cleanup at the
end of your script by deleting all references and objects, which are not needed
anymore.

BUT you cannot control the order in which the references and objects are deleted.

Thus, Python destroyed the reference "Person" to the corrsponding class object
 _before_ it destroyed the "Sophie" instance. So, in the __del__ method
"Person" is not pointing to the class object anymore but to None (why that is
so, is beyond my knowledge). By using the still existing reference
self.__class__, the instance can still refer to the class object.

Confusing? Just remember this: when you want to make sure, the __del__ method
is called at the right time, call it yourself, like this:

del Jason
del Sarah


Cheers, Chris

Attachment: signature.asc
Description: OpenPGP digital signature