大于256小于5的整数缓存

2024-05-14 10:09:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

来自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. :-)

例如

^{pr2}$

提供相同的id

1561854394096
1561854394096

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

{2个id也应该小于1

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代码中的范围是-5到{}(不包括在内)

编辑:

我已经尝试在python2.7和3.6中使用PyCharm。也试过了PythonTutor.com网站在


Tags: ofthetointegersinidthat数字
1条回答
网友
1楼 · 发布于 2024-05-14 10:09:07

在mint python3.6.3(以及2)上,我无法复制。我的猜测是PyCharm或pythontutor在解释之前用某种东西包装了运行-因为这些不是开放代码,我们看不到内部,所以我无法验证。我认为这是真的,原因是while(下面的一切都是mint Python 3):

>>> x=2571299123876321621378
>>> y=2571299123876321621378
>>> print(id(x),id(y))
140671727739528 140671727739808

你可以这样:

^{pr2}$

因此,将这两个整数包装在解释器可以编译的东西中允许这些额外的优化——比如对两个定义使用相同的常量。注意这也是有限的:

>>> def bla():
...  x=2571299123876321621378
...  y=2571299123876321621378
...  print(id(x),id(y))
...  x+=1
...  y+=1
...  print(id(x),id(y))
...
>>> bla()
140671727755592 140671727755592
140671728111088 140671728108808

这取决于代码256,我不能保证。在

相关问题 更多 >

    热门问题