求教__del__在什么时候开始运行的

求教__del__在什么时候开始运行的

程序代码如下:

[Copy to clipboard] [ - ]
CODE:
class Person:
    '''Represents a person.'''
    populiation=0
    def __init__(self,name):
        '''Initializes the person's data.'''
        self.name=name
        print '(Initializing %s)'%self.name
        Person.populiation+=1
    def __del__(self):
        '''I am dying.'''
        print '%s says bye.'%self.name
        Person.populiation-=1
        if Person.populiation==0:
            print 'I am the last one.'
        else:
            print 'There are still %d people left.'%Person.populiation
    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.populiation==1:
            print 'I am the only person here.'
        else:
            print 'We have %d persons here.'%Person.populiation

swaroop=Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

kalam=Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()

swaroop.sayHi()
swaroop.howMany()

运行结果如下:
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.
在进行垃圾回收时。
你少了个东西,你自己运行下就知道了

swaroop=Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

kalam=Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()

swaroop.sayHi()
swaroop.howMany()

不可能执行__del__,因为你根本没有激活__del__.

__del__在进行垃圾回收时,激活


QUOTE:
原帖由 jubao1hao 于 2006-7-7 12:11 发表
你少了个东西,你自己运行下就知道了

swaroop=Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

kalam=Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()

swaroop.sayHi()
swaroop.howMany ...


如果要激活_del_方法,在原有的代码中能否设置一下,以便于在程序结束时自动执行呢?