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.population jerry = 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
时间: 2024-10-02 10:27:36