Exception AttributeError: "'NoneType' object has no attribute 'population'"

MRAB python at mrabarnett.plus.com
Mon Aug 24 13:50:05 CEST 2015


On 2015-08-24 06:49, 344276105 wrote:
> Hi all,
> I am a python learner. I encountered a problem when i was testing the
> following code. What is strange is that if I replace the object name
> with zhang, the program would be ok. And if I replace the
> Person.population with self.__class__.population, it will also be ok. So
> what is the matter?
> Here is the code,
>
> #!/usr/bin/python
> # Filename: objvar.py
>
> class Person:
>          population = 0
>
>          def __init__(self, name):
>                  self.name = name
>                  print '(Initializing %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):
>                  print 'Hi, my name is %s.' % self.name
>
>          def howMany(self):
>                  if Person.population == 1:
>                          print 'I am the only person here.'
>                  else:
>                          print 'We have %d persons here.' % Person.population
>
>
> zhangsan = Person('Swaroop')
> zhangsan.sayHi()
> zhangsan.howMany()
>
> lisi = Person('LiSi')
> lisi.sayHi()
> lisi.howMany()
>
> zhangsan.sayHi()
> zhangsan.howMany()
>
The error occurs because the program has finished and Python is cleaning up.

Unfortunately, it looks like when the __del__ methods run, the Person
class has already been cleaned up (Person is None at that point).

It looks like that behaviour was fixed in Python 3.2.

By the way, it's recommended that you use the latest version of Python
3 unless you require Python 2 because of some dependency on something
that doesn't (yet?) work on Python 3.



More information about the Python-list mailing list