免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 9234 | 回复: 6
打印 上一主题 下一主题

python的一个对象删除的问题,困扰许久 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-05-24 19:23 |只看该作者 |倒序浏览
自己编写了一个Time类,其中有一个类属性count表示当前的实例个数,在__init__中Time.count+=1在__del__中Time.count-=1

然后在shell中交互如下:
from TimeClass import Time
t1=Time()
t2=Time(12,36,6)
t3=t2
print Time.count
2               //这个可以理解是因为t3只是t2的一个浅拷贝
del t2
t3.printTime()
12:36:6     //这个我不知道为什么?难道t2的空间没收回
print Time.count
2                //为什么还是2
del t3
print Time.count
2                  //居然还是2
del t1
print Time.count
1                  //终于是一了,可一个实例也没有了啊
本人很疑惑,到底del命令和__del__方法具体的实现机制是怎样的啊,望高手指点,谢谢了。

论坛徽章:
0
2 [报告]
发表于 2006-05-25 10:03 |只看该作者
自己顶一个先

论坛徽章:
0
3 [报告]
发表于 2006-05-25 14:30 |只看该作者
我想可能是你自己的程序问题
class Test:
    count=0
    def __init__(self):
        Test.count+=1
    def __del__(self):
        Test.count-=1
t1 = Test()
t2 = Test()
t3 = t2
print Test.count
del t2
print t3
del t3
print  Test.count
我这个没问题
如果按照java的思路,应该好解决,del删除只是删除了堆栈里面的变量,只要对象实例仍然有引用
垃圾回收不会回收它

论坛徽章:
0
4 [报告]
发表于 2006-05-26 00:49 |只看该作者
  1. >>> a = Time()
  2. >>> b = Time()
  3. >>> c = b
  4. >>> vars()
  5. {'a': <INsClassNB.Time instance at 0xb7dc40ac>, 'c': <INsClassNB.Time instance at 0xb7dc420c>, 'b': <INsClassNB.Time instance at 0xb7dc420c>, '__builtins__': <module '__builtin__' (built-in)>, 'Time': <class INsClassNB.Time at 0xb7e54efc>, '__name__': '__main__', '__doc__': None}
复制代码


看到了吗,b和c在内存中的位置是一样的,他们是同一个object的不同reference。 只要这个object还在(对这个object的reference数不为0),你怎么del 都是对这个object的reference进行操作, 这个操作是不会触发__del__(self) 的。

论坛徽章:
0
5 [报告]
发表于 2006-05-26 01:03 |只看该作者
In previous versions of Python, there were situations where reference counting failed, and Python couldn't clean up after you.If you created two instances that referenced each other (for instance, a doubly-linked list, where each node has a pointer to the previous and next node in the list), neither instance would ever be destroyed automatically because Python (correctly) believed that there is always a reference to each instance. Python 2.0 has an additional form of garbage collection called “mark-and-sweep” which is smart enough to notice this virtual gridlock and clean up circular references correctly.

难道你用的是老-版本的python??

论坛徽章:
0
6 [报告]
发表于 2006-05-26 10:33 |只看该作者
谢谢,我用的是新版本的python,而如你所说,我的问题只出现过两次,其他时候再试又好了,原理是知道的,可实际是它有时并没有按照原理的样子行为,当然我用了komodo IDE,是不是因为这个关系引起了什么,或者是我的系统太庞大,又是win,有些意想不到的情况就不得而知了,谢谢你的解答,看来还是不予追究了,回头在linux下用命令行多试下,看看还会不会再出现问题,阿门。

论坛徽章:
0
7 [报告]
发表于 2006-05-26 13:37 |只看该作者
现在的python版本很稳定的,差不多两年没有出现过内存泄露bug了。。
komodo 带的python版本好像是他自家修改的  Active python
恐怕是这个特殊python版本的问题。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP