我最近在擺弄id
,並意識到(c?)Python做了一些非常合理的事情:它確保小的整數始終具有相同的id
。python添加小整數時幕後會發生什麼?
>>> 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]
但是,後來我想到了數學運算的結果是否也是如此。原來它是:
>>> 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失敗...
>>> a, b = 200 + 56, 256
>>> id(a) == id(b)
True
>>> a, b = 200 + 57, 257
>>> id(a) == id(b)
False
但有時還是甚至更大的數字作品:
>>> [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如何做到這一點?
數字越大,會發生什麼?有時候ID仍然是一樣的。它正在做一個哈希查找什麼的? – jsau 2011-05-23 18:46:56
@jsau:我編輯了我的答案以包含該內容。 – Daenyth 2011-05-23 18:50:24
@Daenyth,是的,但有時它不是一個新對象;如我的例子所示,有時'2 * x + y'返回與'300 + x'相同的對象。或者我誤解了什麼'ID'呢? – jsau 2011-05-23 18:55:24