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程序设计有所帮助。

相关文章

Python Queue模块详解

Python中,队列是线程间最常用的交换数据的形式。Queue模块是提供队列操作的模块,虽然简单易用,但是不小心的话,还是会出现一些意外。 创建一个“队列”对象 import Queue...

python检测lvs real server状态

复制代码 代码如下:import httplibimport osimport time def check_http(i):    try: &...

Pycharm+Python+PyQt5使用详解

Pycharm+Python+PyQt5使用详解

1,打开cmd安装PyQt5 pip install pyqt5 2,PyQt5不再提供Qt Designer等工具,所以需要再安装pyqt5-tools pip instal...

python pandas生成时间列表

python生成一个日期列表 首先导入pandas import pandas as pd def get_date_list(begin_date,end_date): date...

python 自定义对象的打印方法

在python中,如果不重写自定义对象的__str__方法,打印出来的对象是一串类似于<__main__.Bean object at 0x1007da470>的字符串。这当...