python nonetype异常_python异常属性错误:“'NoneType'对象没有'var'属性”

我将代码更改为在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属性会导致异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值