python 入门级问题,关于__del__

jialejiahi 2011-11-01 01:29:02
初学者,看a byte of python上的一个例子,出了个异常看不出来原因,大家帮忙看看:

#!/usr/bin/python
# Filename: objvar.py

class 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.population
ljia = Person ('ljia')
ljia.say_hi ()
ljia.how_many ()
zhanzhao = Person ('zhanzhao')
zhanzhao.say_hi ()
zhanzhao.how_many ()
ljia.say_hi ()
ljia.how_many ()

运行结果:

(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 left
zhanzhao says bye.
Exception AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.__del__ of <__main__.Person instance at 0xb76ad8ec>> ignored

前面析构可以啊,后面析构怎么就出问题了?
...全文
162 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jialejiahi 2011-11-01
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 iambic 的回复:]

C++用户吗?折腾del干什么。
[/Quote]
嗯,刚看python,不是想折腾它,就是这个异常不明白原因呢。
程序很短,劳烦帮忙看下。
iambic 2011-11-01
  • 打赏
  • 举报
回复
C++用户吗?折腾del干什么。
iambic 2011-11-01
  • 打赏
  • 举报
回复
因为执行的时候__main__里的Person已经被删了。
Person和zhanzhao一样,都是__main__ module里的两个属性。之所以程序会调用zhanzhao的__del__,就是因为这个__main__模块退出的时候已经把zhanzhao的引用从模块里删掉了。那么Person自然也要删掉,而且可能删掉的更早。
一个解决方案是把Person换成self.__class__。
不过你最好别在这种地方浪费时间。使用__del__的代码基本都是错误的。Python不是C++。

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧