python 入门级问题,关于__del__
初学者,看a byte of python上的一个例子,出了个异常看不出来原因,大家帮忙看看:
- Python code
#!/usr/bin/python# Filename: objvar.pyclass Person: ''' Represents a person ''' population = 0 def __init__ (self, name): '''Initializes the person's data.''' self.name = name print '(Initializeing %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 say_hi (self): '''Greeting by the person.''' print 'Hi, my name is %s.' %self.name def how_many (self): if Person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.' %Person.populationljia = Person ('ljia')ljia.say_hi ()ljia.how_many ()zhanzhao = Person ('zhanzhao')zhanzhao.say_hi ()zhanzhao.how_many ()ljia.say_hi ()ljia.how_many ()
运行结果:
- Python code
(Initializeing ljia)Hi, my name is ljia.I am the only person here.(Initializeing zhanzhao)Hi, my name is zhanzhao.We have 2 persons here.Hi, my name is ljia.We have 2 persons here.ljia says bye.There are still 1 people leftzhanzhao says bye.Exception AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.__del__ of <__main__.Person instance at 0xb76ad8ec>> ignored
前面析构可以啊,后面析构怎么就出问题了?
[解决办法]
因为执行的时候__main__里的Person已经被删了。
Person和zhanzhao一样,都是__main__ module里的两个属性。之所以程序会调用zhanzhao的__del__,就是因为这个__main__模块退出的时候已经把zhanzhao的引用从模块里删掉了。那么Person自然也要删掉,而且可能删掉的更早。
一个解决方案是把Person换成self.__class__。
不过你最好别在这种地方浪费时间。使用__del__的代码基本都是错误的。Python不是C++。