我将代码更改为在Python2.7上运行,并添加了一些打印内容,结果如下:# So I changed the code as follows:
class Robot:
population = 0 #class variable, number of robots
def __init__(self, name):
self.name = name
print '(initializing %s)' % self.name
Robot.population += 1
def __del__(self):
print'%s is being destroyed!' % self.name
print 'pre1 %s type %s' % (Robot, type(Robot))
Robot.population -= 1
print 'pre2'
if Robot.population == 0:
print '%s was the last one.' % self.name
else:
print 'there are still %d robots working.' % Robot.population
def sayHi(self):
print '%s says hi' % self.name
def howMany():
print 'there are %d robots' % Robot.population
howMany = staticmethod(howMany)
#instantiate 2 robots
mingos = Robot('alvergas')
mingos.sayHi()
Robot.howMany()
print 'end program'
# and the output is:
(initializing alvergas)
alvergas says hi
there are 1 robots
end prog
alvergas is being destroyed!
pre1 None type
Exception AttributeError: "'NoneType' object has no attribute 'population'" in
> ignored
所以异常发生在程序结束之后。
正如^{} description所说:“当__del__()被调用以响应被删除的模块时(例如,当程序执行完成时),__del__()方法引用的其他全局变量可能已经被删除或正在被删除(例如,导入机关机)。”
我认为在您的例子中,当类机器人已经被拆下时,就调用了Robot.population -= 1行,变得没有。尝试访问None属性会导致异常。