jialejiahi 2011年11月01日
python 入门级问题,关于__del__
初学者,看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

前面析构可以啊,后面析构怎么就出问题了?
...全文
100 点赞 收藏 3
写回复
3 条回复

还没有回复,快来抢沙发~

发动态
发帖子
脚本语言(Perl/Python)
创建于2007-08-27

1.5w+

社区成员

3.3w+

社区内容

其他开发语言 脚本语言(Perl ,Python)
社区公告
暂无公告