python中__del_____在python中不需要调用del\uuu方法

我是python新手,一直在研究Swaroop CH的“python字节”中的示例。我看到了一些使用__del__方法的行为,这让我很困惑。在

基本上,如果我运行以下脚本(在python2.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 = Person4('Kalem')

使用Python控制台(或Spyder interactive控制台),我可以看到以下内容:execfile(u'C:\1_eric\Python\test1.py')

Initializing Swaroop

Initializing Kalem

execfile(u'C:\1_eric\Python\test1.py')

Initializing Swaroop

Swaroop says bye

I am the last one

Initializing Kalem

Kalem says bye

I am the last one

为什么在第二次运行__init__之后立即调用__del__方法?

我猜,由于使用了相同的实例名('swaroop'和'kaleem'),所以它正在释放原始实例并对其进行垃圾回收。但是,这似乎在破坏目前的人口统计。在

这是怎么回事?

什么是避免这种混乱的好方法?

避免使用__del__?

在重用之前检查现有的实例名称?

... 在

谢谢,

埃里克

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值