来自sys.getrefcount的意外结果 [英] Unexpected result from sys.getrefcount
问题描述
当我输入时:
>>> astrd = 123
>>> import sys
>>> sys.getrefcount(astrd)
3
>>>
我没有得到使用 astrd
的地方3次?
它不是 astrd
但值 123
。 astrd
仅仅是(不可变的)数字123的名称,可以多次引用。除此之外,小整数通常是共享的:
>>> astrd = 123
>>> sys.getrefcount(astrd)
4
>>> j = 123
>>> sys.getrefcount(astrd)
5
在第二个任务中,没有创建新的整数,而不是 j
只是整数 123
的新名称。
然而,给定非常大的整数,这并不成立:
>>> i = 823423442583
>>> sys.getrefcount(i)
2
>>> j = 823423442583
>>> sys.getrefcount(i)
2
共享整数是CPython的实现细节其他)。由于小整数经常被实例化,共享它们会节省大量的内存。这是因为整数是不可变的这一事实。
有关第二个示例中的附加参考,请参阅参考资料。 codeape的答案。
When I typed:
>>> astrd = 123
>>> import sys
>>> sys.getrefcount(astrd)
3
>>>
I am not getting where is astrd
used 3 times ?
It's not astrd
that is referenced three times, but the value 123
. astrd
is simply a name for the (immutable) number 123, which can be referenced however many times. Additionally to that, small integers are usually shared:
>>> astrd = 123
>>> sys.getrefcount(astrd)
4
>>> j = 123
>>> sys.getrefcount(astrd)
5
In the second assignment, no new integer is created, instead j
is just a new name for the integer 123
.
However, given very large integers, this does not hold:
>>> i = 823423442583
>>> sys.getrefcount(i)
2
>>> j = 823423442583
>>> sys.getrefcount(i)
2
Shared integers are an implementation detail of CPython (among others). Since small integers are instantiated very often, sharing them saves a lot of memory. This is made possible by the fact that integers are immutable in the first place.
For the additional reference in the second example, cf. codeape's answer.
这篇关于来自sys.getrefcount的意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!