python异常AttributeError:"'NoneType'对象没有属性'var'"

man*_*urt 1 python exception

我在Python中获得此异常,

Exception AttributeError: "'NoneType' object has no attribute 'population'" in del of <main.Robot instance at 0x104eb7098>> ignored
Run Code Online (Sandbox Code Playgroud)

这是我的代码,

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()
Run Code Online (Sandbox Code Playgroud)

谢谢!

ego*_*r83 6

我更改了代码以在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
Run Code Online (Sandbox Code Playgroud)

因此在程序结束后发生异常.正如__del__描述所说:"当__del__()响应于被删除的模块而被调用时(例如,当完成程序的执行时),该__del__()方法引用的其他全局变量可能已经被删除或者正在被拆除(例如导入)机器关闭)."

我认为在你的情况下,Robot.population -= 1当类机器人已被拆除时,该行被调用,变为无.尝试访问None属性会导致异常.