python的类设计中,运行两次之后就会出现每次调用__init__(self,name)之后就直接调用 __del__(self)的情况,这是啥原因导致的?
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
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
[解决办法]
测试了下,没看出有啥毛病。LZ用自己输出结果说明一下问题吧...
[解决办法]
在交互模式执行同直接运行脚本有点不同。直接运行嘛,当执行完最后一行,每个person对象引用数应该都没啦,__del__是会自动调用多次,这是类的正常机制,不过交互模式下会增加对象的引用,__del__通常不会执行,后续才能继续观察变量。不过这样个人觉得反倒看不出类的析构机制来...