来自 sys.getrefcount 的意外结果

2023-07-05Python开发问题
0

本文介绍了来自 sys.getrefcount 的意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

当我输入时:

>>> astrd = 123
>>> import sys
>>> sys.getrefcount(astrd)
3
>>> 

我不知道 astrd 在哪里使用了 3 次?

I am not getting where is astrd used 3 times ?

推荐答案

被引用3次的不是astrd,而是值123.astrd 只是(不可变)数字 123 的名称,可以多次引用.除此之外,通常共享小整数:

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

在第二个赋值中,没有创建新的整数,而是 j 只是整数 123 的新名称.

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

共享整数是 CPython(以及其他)的一个实现细节.由于小整数经常被实例化,共享它们可以节省大量内存.这是因为整数是不可变的.

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.

有关第二个示例中的附加参考,请参阅.codeape 的回答.

For the additional reference in the second example, cf. codeape's answer.

这篇关于来自 sys.getrefcount 的意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10