首页 > 代码库 > Python python __def__ Exception AttributeError: "'NoneType' object has no attribute
Python python __def__ Exception AttributeError: "'NoneType' object has no attribute
class Person: ‘‘‘Represents a person.‘‘‘ population = 0 def __init__(self,name): ‘‘‘Initializes the person‘s data.‘‘‘ self.name = name print ‘(Initializing %s)‘ % self.name Person.population +=1 def __del__(self): ‘‘‘I am dying.‘‘‘ print ‘%s says bye.‘ % self.name Person.population -=1 if Person.population == 0: print ‘I am the last one.‘ else: print ‘There are still %d people left.‘ % Person.population def sayHi(self): ‘‘‘Greeting by the person. Really, that‘s all it does.‘‘‘ print ‘Hi, my name is %s.‘ % self.name def howMany(self): ‘‘‘Prints the current population.‘‘‘ if Person.population == 1: print ‘I am the only person here.‘ else: print ‘We have %d persons here.‘ % Person.populationjerry = Person(‘Jerry‘)jerry.sayHi()jerry.howMany()qiu = Person(‘Qiu‘)qiu.sayHi()qiu.howMany()jerry.sayHi()jerry.howMany()
出现如下错误:
Exception AttributeError: "‘NoneType‘ object has no attribute ‘population‘" in <bound method Person.__del__ of <__main__.Person instance at 0x01AF97D8>> ignored
原因如下:At interpreter shutdown, the module‘s global variables are set to None before the module itself is released.__del__ methods may be called in those precaries circumstances, and should not rely on any global state.将__del__方法中对类变量的访问方式改为如下即可:def __del__(self): self.__class__.population -= 1
Python python __def__ Exception AttributeError: "'NoneType' object has no attribute
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。