Possible Duplicate:
Python “is” operator behaves unexpectedly with integers
我偶然发现了以下 Python怪异:
>>> two = 2
>>> ii = 2
>>> id(two) == id(ii)
True
>>> [id(i) for i in [42,42,42,42]]
[10084276, 10084276, 10084276, 10084276]
>>> help(id)
Help on built-in function id in module __builtin__:
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
- 每个数字都是唯一的对象吗?
- 不同的变量是否持有相同的元素值(例如,两个,ii)同一个对象?
- Python如何生成数字的id?
- 在上面的例子中,两个和 ii 是指向一个存储单元的指针,它的值是 2?那会非常奇怪。
帮我解开这个身份危机。
还有一些怪事:
>>> a,b=id(0),id(1)
>>> for i in range(2,1000):
a,b=b,id(i)
if abs(a-b) != 12:
print('%i:%i -> %i' % (i,a,b))
上面的代码检查连续整数的 id 是否也是连续的,并打印出 异常:
77:10083868 -> 10085840
159:10084868 -> 10086840
241:10085868 -> 10087840
257:10087660 -> 11689620
258:11689620 -> 11689512
259:11689512 -> 11689692
260:11689692 -> 11689548
261:11689548 -> 11689644
262:11689644 -> 11689572
263:11689572 -> 11689536
264:11689536 -> 11689560
265:11689560 -> 11689596
266:11689596 -> 11689656
267:11689656 -> 11689608
268:11689608 -> 11689500
331:11688756 -> 13807288
413:13806316 -> 13814224
495:13813252 -> 13815224
577:13814252 -> 13816224
659:13815252 -> 13817224
741:13816252 -> 13818224
823:13817252 -> 13819224
905:13818252 -> 13820224
987:13819252 -> 13821224
请注意,模式从 413 开始出现。可能是因为在每个新内存页面的开头都有一些巫术记账。
最佳答案
-1 到 255(?) 之间的整数,以及字符串文字,都被保留。源中的每个实例实际上代表同一个对象。
在CPython中,id()
的结果是PyObject在进程空间中的地址。
关于Python身份: Multiple personality disorder,需要代码收缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2058948/