Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #95610

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

Subject Re: Exception AttributeError: "'NoneType' object has no attribute 'population'"
References <tencent_0E0131CC082F94256284E989@qq.com>
From MRAB <python@mrabarnett.plus.com>
Date 2015-08-24 12:50 +0100
Newsgroups comp.lang.python
Message-ID <mailman.13.1440417014.11709.python-list@python.org> (permalink)

Show all headers | View raw


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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Exception AttributeError: "'NoneType' object has no attribute 'population'" MRAB <python@mrabarnett.plus.com> - 2015-08-24 12:50 +0100

csiph-web