我正在从这个网页学习Python (它是中文的,请只关注代码。)我想在Windows 7上使用Python 2.7.3自己练习代码。但是我发现对象名称有一个非常奇怪的错误. 代码如下:
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the person\'s data.'''
self.name = name
print '(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
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
David = Person('David')
David.sayHi()
David.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
David.sayHi()
David.howMany()
运行这些代码时,我收到了这个错误报告(最后两行)。但是当我用“Swaroop”或其他名称替换对象变量“David”时,代码可以正常工作!我不知道这是怎么发生的。
(Initializing David)
Hi, my name is David.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is David.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
David says bye.
Exception AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.
__del__ of <__main__.Person instance at 0x00000000026D91C8>> ignored