Python引用计数操作示例

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

解决torch.autograd.backward中的参数问题

解决torch.autograd.backward中的参数问题

torch.autograd.backward(variables, grad_variables=None, retain_graph=None, create_graph=False...

python numpy 部分排序 寻找最大的前几个数的方法

如下所示: import numpy as np K=4 a = np.array([0, 8, 0, 4, 5, 8, 8, 0, 4, 2]) a[np.argpartition...

详解Python用户登录接口的方法

详解Python用户登录接口的方法

Readme: blog address: 摘要:编写登录接口 输入用户名、密码 认证成功后显示欢迎信息 输错3次后锁定 关键词:循环;判断;外部数据读写;列表;字典; 展望:可以结合数...

Python itertools模块详解

这货很强大, 必须掌握 文档 链接 http://docs.python.org/2/library/itertools.html pymotw 链接 http://pymotw.com...

深入浅析ImageMagick命令执行漏洞

深入浅析ImageMagick命令执行漏洞

00 前言 什么是ImageMagick? ImageMagick是一个功能强大的开源图形处理软件,可以用来读、写和处理超过90种的图片文件,包括流行的JPEG、GIF、 PNG、PDF...