本篇文章为大家展示了如何在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项目中引用计数,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注天达云行业资讯频道。