Hello, I'm trying to execute this simple code:

class Person:
  population = 0
  def __init__(self, name):
    print 'Creating % s peron' % name
    self.name = name
    Person.population += 1
  def __del__(self):
    print 'Destroying %s person' % self.name
    Person.population -= 1
    
 
prvi = Person('Asimi')
drugi = Person('Mici')

I'm using Wing IDE trial and here's what is output in debug mode:

Creating Asimi peron
Creating Mici peron
Destroying Mici person
Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.__del__ of <__main__.Person instance at 0x00B29558>> ignored
Destroying Asimi person
Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.__del__ of <__main__.Person instance at 0x00B29530>> ignored

Problem is solved by putting self.population - = 1 in __del__ method, but the example is from book ByteOfPython and population is supposed to be class variable...

I really don't have a clue what is wrong here...

It looks like you haven't included all the code you wrote to test this. Were there statements after 'drugi = Person('Mici')'? Statements like, perhaps:

del drugi
del prvi

If so, please include them, because the other code worked fine for me.

Look at variable k in the code snippet at:
http://www.daniweb.com/code/snippet354.html
This is a similar situation, it is declared outside of the class methods and needs self to bring it into the methods. The class name won't do. If your book uses this, then it is wrong (can happen). Maybe very early versions of Python allowed this.

Remember, special method __init__() is called first and acts as constructor. Special method __del__() acts as the mostly optional destructor.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.