im getting this exception in Python,
Exception AttributeError: "'NoneType' object has no attribute 'population'" in del of <main.Robot instance at 0x104eb7098>> ignored
this is my code,
class Robot:
population = 0 #class variable, number of robots
def __init__(self, name):
self.name = name
print ('(initializing {0})'.format(self.name))
Robot.population += 1
def __del__(self):
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print ('{0} was the last one.'.format(self.name))
else:
print('there are still {0:d} robots working.'.format(Robot.population))
def sayHi(self):
print('hole mi mestre me llama {0}'.format(self.name))
def howMany():
print('hay {0:d} robots'.format(Robot.population))
howMany = staticmethod (howMany)
#instantiate 2 robots
mingos = Robot('alvergas')
mingos.sayHi()
Robot.howMany()
pingos = Robot('chupacabra')
pingos.sayHi()
Robot.howMany()
#destroy one
del mingos
Robot.howMany()
Thanks!
I changed the code to run on Python 2.7 and added some prints, here’s the result:
So the exception occurs after the program ends.
As
__del__description says: “when__del__()is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the__del__()method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down).”I think that in your case the line
Robot.population -= 1is called when the class Robot has already been torn down, becoming None. Trying to access an attribute of None causes an exception.