本文實例講述了Python引用計數操作。分享給大家供大家參考,具體如下:
為了簡化內存管理,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 l2print l_refanother_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 moduledef time_2(x): return 2 * xdis.dis(time_2)print "*"*20dis.dis(get_ref)
結合上述代碼,測試示例如下:
import ctypesimport dis # bytecode disassembler moduledef 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 * xdis.dis(time_2)print "*"*20dis.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)
新聞熱點
疑難解答