gpt4 book ai didi

python - 整数为 0 的 ref 计数器的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-03 11:04:51 25 4
gpt4 key购买 nike

我正在摆弄 python 的 ctypes 模块,以更好地理解垃圾收集器的工作原理。在解释器中玩,我经历了这种奇怪的情况:

>>>import ctypes
>>>def get_ref(obj):
... """ This returns the refcount of obj as a c_size_t """
... return ctypes.c_size_t.from_address(id(obj))
...
>>>myInt = 0
>>>get_ref(myInt)
c_ulong(283L)

为什么 myInt 似乎被 Python 引用了 283 次?我错过了什么吗?

感谢您的见解。

最佳答案

在 int 的 CPython 实现中,引用 [-5 ; 256] 被共享。

如果您使用 myInt = 257,您应该按预期获得 c_ulong(1L) 的结果。

请看这个link了解详情。

关于python - 整数为 0 的 ref 计数器的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22734064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com