小编ELe*_*Lee的帖子

当不期望时,在python中调用__del__方法

我是python的新手,并且一直在研究Swaroop CH的"A Byte of Python"中的示例.我看到一些__del__令我困惑的方法的行为.

基本上,如果我运行以下脚本(在Python 2.6.2中)

class Person4:
    '''Represents a person'''
    population = 0

    def __init__(self, name):
        '''Initialize the person's data'''
        self.name = name
        print 'Initializing %s'% self.name

        #When the person is created they increase the population
        Person4.population += 1

    def __del__(self):
        '''I am dying'''
        print '%s says bye' % self.name

        Person4.population -= 1

        if Person4.population == 0:
            print 'I am the last one'
        else:
            print 'There are still %d left' % Person4.population


swaroop = Person4('Swaroop')
kaleem …
Run Code Online (Sandbox Code Playgroud)

python object-lifetime del

6
推荐指数
2
解决办法
2139
查看次数

标签 统计

del ×1

object-lifetime ×1

python ×1