当python添加小的整数时,幕后会发生什么? [英] What happens behind the scenes when python adds small ints?
问题描述
我最近在 id
中摆弄并且意识到(c?)Python做了一些非常明智的事情:它确保小的int总是具有相同的 ID
。
I was fiddling around with id
recently and realized that (c?)Python does something quite sensible: it ensures that small ints always have the same id
.
>>> a, b, c, d, e = 1, 2, 3, 4, 5
>>> f, g, h, i, j = 1, 2, 3, 4, 5
>>> [id(x) == id(y) for x, y in zip([a, b, c, d, e], [f, g, h, i, j])]
[True, True, True, True, True]
但是我想知道是否真的如此对于数学运算的结果。原来是:
But then it occurred to me to wonder whether the same is true for the results of mathematical operations. Turns out it is:
>>> nines = [(x + y, 9) for x, y in enumerate(reversed(range(10)))]
>>> [id(x) == id(y) for x, y in nines]
[True, True, True, True, True, True, True, True, True, True]
似乎它开始在n = 257失败...
Seems like it starts failing at n=257...
>>> a, b = 200 + 56, 256
>>> id(a) == id(b)
True
>>> a, b = 200 + 57, 257
>>> id(a) == id(b)
False
但有时甚至还能正常工作数字越大:
But sometimes it still works even with larger numbers:
>>> [id(2 * x + y) == id(300 + x) for x, y in enumerate(reversed(range(301)))][:10]
[True, True, True, True, True, True, True, True, True, True]
这里发生了什么? python如何做到这一点?
What's going on here? How does python do this?
推荐答案
Python保留了一个 int
的池一定数量的物体。当您在该范围内创建一个时,您实际上会获得对已存在的一个的引用。我怀疑这是出于优化原因。
Python keeps a pool of int
objects in certain numbers. When you create one in that range, you actually get a reference to the pre-existing one. I suspect this is for optimization reasons.
对于超出该池范围的数字,只要您尝试制作一个新对象,就会出现这种情况。
For numbers outside the range of that pool, you appear to get back a new object whenever you try to make one.
$ python
Python 3.2 (r32:88445, Apr 15 2011, 11:09:05)
[GCC 4.5.2 20110127 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 300
>>> id(x)
140570345270544
>>> id(100+200)
140570372179568
>>> id(x*2)
140570345270512
>>> id(600)
140570345270576
PyObject * PyInt_FromLong( long ival)
返回值:新参考。创建
新的整数对象,其值为
ival。
PyObject* PyInt_FromLong(long ival) Return value: New reference. Create a new integer object with a value of ival.
当前实现保留
整数对象数组对于-5到256之间的所有
整数,当你
在该范围内创建一个int时,
实际上只是返回对现有对象
的引用。所以它应该是
可能改变值1. I
怀疑Python在
中的行为这种情况是未定义的。 : - )
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. :-)
强调我的
这篇关于当python添加小的整数时,幕后会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!