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

Jp Calderone exarkun at divmod.com
Sat Sep 17 21:49:16 EDT 2005


On Sun, 18 Sep 2005 02:10:50 +0100, Jason <jason at jasonmhirst.co.uk> wrote:
>Hi,
>
>I'm following a tutorial about classes, and have created the following
>(well, copied it from the manual buy added my own and wifes names)...
>
>class Person:
>     population=0
>
>     def __init__(self,name):
>         self.name=name
>         print '(Initialising %s)' % self.name
>         Person.population += 1
>
>     def __del__(self):
>         print "%s says bye." % self.name
>
>         Person.population -= 1
>
>         if Person.population == 0:
>             print "I am the last one"
>         else:
>             print "There are still %d people left." % Person.population
>
>     def sayHi(self):
>         '''Greeting by the person.
>
>         That's all it does.'''
>         print "Hi, my name is %s" % self.name
>
>     def howMany(self):
>         if Person.population==1:
>             print "I am on the only person here."
>         else:
>             print "We have %d persons here." % Person.population
>
>Jason=Person("Jason")
>Jason.sayHi()
>Jason.howMany()
>
>Sophie=Person("Sophie")
>Sophie.sayHi()
>Sophie.howMany()
>
>Jason.sayHi()
>
>The code, when run, should produce the following...
>
>Hi, my name is Jason.
>I am the only person here.
>(Initializing Sophie)
>Hi, my name is Sophie.
>We have 2 persons here.
>Hi, my name is Jason.
>We have 2 persons here.
>Jason says bye.
>There are still 1 people left.
>Sophie says bye.
>I am the last one.
>
>But what I actually get is...
>
>(Initialising Jason)
>Hi, my name is Jason
>I am on the only person here.
>(Initialising Sophie)
>Hi, my name is Sophie
>We have 2 persons here.
>Hi, my name is Jason
>We have 2 persons here.
>Jason says bye.
>There are still 1 people left.
>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 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.
>
>TIA

The __del__ method is not a reliable cleanup mechanism.  It runs when an object is garbage collected, but garbage collection is unpredictable and not guaranteed to ever occur.

In your particular case, __del__ is running during interpreter shut down.  Another part of interpreter shutdown is to set the attributes of all modules to None.  Your code executes after this, tries to change None.population (since Person is now None), and explodes.

Your best bet is not to use __del__ at all.  Instead, add a method to be invoked when a person is going away, and then invoke it.

Jp



More information about the Python-list mailing list