问题
is
in Python tests if 2 references point to the same object.
Numbers between -5 and 256 are cached internally so:
a = 10
b = 10
a is b # Results in True
How does this explain something like:
20000 is 20000 # Results in True
Both numbers are above 256. Should not the 2 integers be 2 distinct objects?
回答1:
The Python interpreter sees you are re-using a immutable object, so it doesn't bother to create two:
>>> import dis
>>> dis.dis(compile('20000 is 20000', '', 'exec'))
1 0 LOAD_CONST 0 (20000)
3 LOAD_CONST 0 (20000)
6 COMPARE_OP 8 (is)
9 POP_TOP
10 LOAD_CONST 1 (None)
13 RETURN_VALUE
Note the two LOAD_CONST
opcodes, they both load the constant at index 0:
>>> compile('20000 is 20000', '', 'exec').co_consts
(20000, None)
In the interactive interpreter Python is limited to having to compile each (simple or compound) statement you enter separately, so it can't reuse these constants across different statements.
But within a function object it certainly would only create one such integer object, even if you used the same int literal more than once. The same applies to any code run at the module level (so outside of functions or class definitions); those all end up in the same code object constants too.
回答2:
Python stores objects in memory to make things more efficient. It only needs to assign one block of memory to 20000
, and so both references point to the same block of memory, resulting in True
.
来源:https://stackoverflow.com/questions/37144600/why-does-20000-is-20000-result-in-true