当前位置: 移动技术网 > IT编程>脚本编程>Python > Python引用计数操作示例

Python引用计数操作示例

2018年09月23日  | 移动技术网IT编程  | 我要评论

织毛衣花样,婚假申请书范文,小彩泉

本文实例讲述了python引用计数操作。分享给大家供大家参考,具体如下:

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

import ctypes
def 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 =l
l_ref = get_ref(l)
print l_ref
del l
print l_ref
del l2
print l_ref
another_list = [0, 0, 7]
a_ref = get_ref(another_list)
print a_ref

输出:

c_ulong(2l)
c_ulong(1l)
c_ulong(0l)
c_ulong(1l)

运行结果如下图所示:

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

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

结合上述代码,测试示例如下:

import ctypes
import dis # bytecode disassembler module
def get_ref(obj):
  """ returns a c_size_t, which is the refcount of obj """
  return ctypes.c_size_t.from_address(id(obj))
def time_2(x):
  return 2 * x
dis.dis(time_2)
print "*"*20
dis.dis(get_ref)

运行结果:

  7           0 load_const               1 (2)
              3 load_fast                0 (x)
              6 binary_multiply    
              7 return_value       
********************
  5           0 load_global              0 (ctypes)
              3 load_attr                1 (c_size_t)
              6 load_attr                2 (from_address)
              9 load_global              3 (id)
             12 load_fast                0 (obj)
             15 call_function            1
             18 call_function            1
             21 return_value       

更多关于python相关内容感兴趣的读者可查看本站专题:《python函数使用技巧总结》、《python数学运算技巧总结》、《python数据结构与算法教程》、《python字符串操作技巧汇总》及《python入门与进阶经典教程

希望本文所述对大家python程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网