我知道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). */
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网站在
在mint python3.6.3(以及2)上,我无法复制。我的猜测是
PyCharm
或pythontutor在解释之前用某种东西包装了运行-因为这些不是开放代码,我们看不到内部,所以我无法验证。我认为这是真的,原因是while(下面的一切都是mint Python 3):你可以这样:
^{pr2}$因此,将这两个整数包装在解释器可以编译的东西中允许这些额外的优化——比如对两个定义使用相同的常量。注意这也是有限的:
这取决于代码256,我不能保证。在
相关问题 更多 >
编程相关推荐