求大佬看一下这个运行是什么意思!!
import sysa = 10
#reference
print(sys.getrefcount(a))
list1 =
list2 = list1
list3 = list1
print(sys.getrefcount(list1))
这是运行结果
19
4 sys.getrefcount接口可以查询对象的引用计数。
如果是统计引用次数,那我感觉 print(sys.getrefcount(a)) 应该是 2,但是我这里是 64
那可能是给分配 a 分配个随机数,然后在同一样的代码下,我在 a = 10 下面加个 b = a ,然后 print(sys.getrefcount(a))65
import sys
a = 11# 常量 分配随机值 假设现在是 63
b = a # 引用过 +1
# reference
print(sys.getrefcount(a)) # sys.getrefcount 也算一次引用 所以输出 65
list1 = # 这个就是 1 了
list2 = list1 # +1
list3 = list1 # +1
print(sys.getrefcount(list1)) # sys.getrefcount 也算一次引用 所以输出 4
大马强 发表于 2022-1-21 10:23
如果是统计引用次数,那我感觉 print(sys.getrefcount(a)) 应该是 2,但是我这里是 64
那可能是给分配 a ...
我查了一下,这个好像和python的回收机制有关联,当它值为零时默认回收掉变量空间
用 del 可以 减一
del list2 # -1
print(sys.getrefcount(list1))# sys.getrefcount 也算一次引用 所以输出 3 本帖最后由 阿奇_o 于 2022-1-21 13:31 编辑
真要理解,首先得明白 对象的本质,其次还要考虑 垃圾回收机制的影响。
我们可以先看看它的文档说明,再做一些验证:
>>> import sys
>>> help(sys.getrefcount)
Help on built-in function getrefcount in module sys:
getrefcount(...)
getrefcount(object) -> integer
Return the reference count of object.The count returned is generally
one higher than you might expect, because it includes the (temporary)
reference as an argument to getrefcount().
>>> sys.getrefcount(1)
865
>>> a = 1
>>> sys.getrefcount(a)
865
>>> ls1 =
>>> sys.getrefcount(ls1)
2
>>> ls2 = ls1
>>> sys.getrefcount(ls2)
3
>>> ls3 = ls2
>>> sys.getrefcount(ls2)
4
>>> sys.getrefcount(ls3)
4
>>> sys.getrefcount(ls1)
4
>>> sys.getrefcount(ls1)
866
>>> b = 1
>>> sys.getrefcount(ls1)
867
>>> sys.getrefcount(1)
868
>>> sys.getrefcount(1)
868
>>>
https://s4.ax1x.com/2022/01/21/72BhIe.png
暂时结论:
对于 非引用类型的对象,这个"引用数量"基本没有什么意义(因为有个人Python环境的因素影响,不可预知)。
对于 引用类型的对象,如 列表、字典、自定义类的实例对象 等,有一定参考意义,即 sys.getrefcount(ref_obj) - 1 即 该对象 最终被引用、被绑定到了 多少个 "字符名"上。
如 这里的 这个列表对象,被绑定到了 ls1, ls2, ls3 这3个 字符名 上,所以共有3个"引用",这和我们的通常预期一致,是可以明确的,所以我说"有一定参考意义"。
(若加上getrefcount的形参的临时绑定,就是再+1个,故共 4 个"引用",这也就是帮助文档里所说 one higher than you might expect)
页:
[1]