[Tutor] __del__ exception

Michael Langford mlangford.cs03 at gtalumni.org
Thu Jun 5 23:57:50 CEST 2008


There is no remaining referent to your class at the point when the
last instance has started to be deleted. This allows the class itself
to be garbage collected. Changing the code to the following will
prevent this.

#!/usr/bin/python

class Person:
        population = 0

        def __init__(self, name):
                self.name = name
                print '%s has been added' %self.name

                Person.population += 1

        def __del__(self):
                print '%s is leaving' % self.name

                Person.population -= 1

                print 'population = %d' %Person.population

cls = Person
p = Person('Jean')
d = Person('Michael')

        --Michael



On Thu, Jun 5, 2008 at 4:14 PM, Blaise Morose <jdeambulemorose at gmail.com> wrote:
> Hi,
>
> I have this silly piece of code that I am experimenting with:
>
> #!/usr/bin/python
>
> class Person:
>         population = 0
>
>         def __init__(self, name):
>                 self.name = name
>                 print '%s has been added' %self.name
>
>                 Person.population += 1
>
>         def __del__(self):
>                 print '%s is leaving' % self.name
>
>                 Person.population -= 1
>
>                 print 'population = %d' %Person.population
>
>
> p = Person('Jean')
> d = Person('Michael')
>
> Output:
>
> Jean has been added
> Michael has been added
> Michael is leaving
> population = 1
> Jean is leaving
> Exception exceptions.AttributeError: "'NoneType' object has no attribute
> 'population'" in <bound method Person.__del__ of <__main__.Person instance
> at 0xb7dadacc>> ignored
>
> So once all objects have been destroyed, an exception is triggered on class
> variable 'population'.
>
> Any more logical explanation and work around? I just need to understand what
> python is doing here
>
> Thx
>
> Blaise
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com


More information about the Tutor mailing list