gpt4 book ai didi

python - 大于 256 小于 -5 的整数缓存

转载 作者:行者123 更新时间:2023-12-05 06:29:48 26 4
gpt4 key购买 nike

我知道 python 有一个小整数的概念,它是从 -5256 之间的数字,如果两个变量分配给这个范围内的相同数字,它们都是将使用相同的底层对象。

来自 Python 文档,

#ifndef NSMALLPOSINTS
#define NSMALLPOSINTS 257
#endif
#ifndef NSMALLNEGINTS
#define NSMALLNEGINTS 5
#endif

/* Small integers are preallocated in this array so that they can be shared. The integers that are preallocated are those in the range -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive). */

还有 explained here,

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)

例子,

a = 255
b = 255
print(id(a))
print(id(b))

给出相同的id,

1561854394096
1561854394096

这是有道理的,也解释了这个答案,"is" operator behaves unexpectedly with integers

如果两个数小于-5,它们也应该有不同的ID,如下所示,

a = -6
b = -6
print(id(a))
print(id(b))

给予,

2827426032208
2827426032272

到目前为止这是有道理的,

但是任何大于256的数字都应该有不同的id,

这应该返回不同的 ID,

a = 257
b = 257
print(id(a))
print(id(b))

但事实并非如此

2177675280112
2177675280112

即使我使用非常大的整数,ID 也是相同的,

a = 2571299123876321621378
b = 2571299123876321621378
print(id(a))
print(id(b))

给我,

1956826139184
1956826139184

有人能告诉我为什么大于 256 的数字具有相同的 ID,即使在 Python 代码中范围是 -5257(不包括在内)

编辑:

我尝试过将 PyCharm 与 Python 2.7 和 3.6 结合使用。还在 PythonTutor.com 上试过

最佳答案

这个问题重复了,回答here

When you run code in a .py script, the entire file is compiled into a code object before executing it. In this case, CPython is able to make certain optimizations

关于python - 大于 256 小于 -5 的整数缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53168093/

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