码迷,mamicode.com
首页 > 编程语言 > 详细

Python python __def__ Exception AttributeError: "'NoneType' object has no attribute

时间:2014-12-16 14:54:30      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:blog   ar   io   os   sp   for   on   div   log   

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

标签:blog   ar   io   os   sp   for   on   div   log   

原文地址:http://www.cnblogs.com/monkeyfather/p/4166993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!