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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…