我在 Python 中得到这个异常,
Exception AttributeError: "'NoneType' object has no attribute 'population'" in del of <main.Robot instance at 0x104eb7098>> ignored
这是我的代码,
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()
谢谢!
请您参考如下方法:
我更改了代码以在 Python 2.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 <type 'NoneType'>
Exception AttributeError: "'NoneType' object has no attribute 'population'" in
<bound method Robot.__del__ of <__main__.Robot instance at 0x0223C918>> ignored
所以异常发生在程序结束之后。 作为__del__ description说:“当 __del__() 被调用以响应模块被删除时(例如,当程序执行完成时), __del__() 引用的其他全局变量方法可能已经被删除或正在被拆除(例如进口机械关闭)。”
我认为在您的情况下,当 Robot 类已被拆除并变为 None 时,将调用 Robot.population -= 1 行。尝试访问 None 的属性会导致异常。
