pyhton中引用计数

来源:互联网 发布:linux 设置dns解析 编辑:程序博客网 时间:2024/06/04 21:47

为了简化内存管理,Python通过引用计数机制实现了自动的垃圾回收功能,Python中的每个对象都有一个引用计数,用来计数该对象在不同场所分别被引用了多少次。每当引用一次Python对象,相应的引用计数就增1,每当消毁一次Python对象,则相应的引用就减1,只有当引用计数为零时,才真正从内存中删除Python对象。

import ctypesdef get_ref(obj):    """ returns a c_size_t, which is the refcount of obj """    return ctypes.c_size_t.from_address(id(obj))l = [1,2,3,4]l2 =ll_ref = get_ref(l)print l_refdel lprint l_refdel l2 print l_refanother_list = [0, 0, 7]a_ref = get_ref(another_list)print a_ref
输出:

D:\test>python test4.py
c_ulong(2L)
c_ulong(1L)
c_ulong(0L)
c_ulong(1L)

另外python编译成字节码的模块为 dis

import dis  # bytecode disassembler moduledef time_2(x):    return 2 * xdis.dis(time_2)print "*"*20dis.dis(get_ref)


0 0