可能重复:
Python"is"运算符使用整数意外运行
今天我试着调试我的项目,经过几个小时的分析,我得到了这个:
>>> (0-6) is -6
False
Run Code Online (Sandbox Code Playgroud)
但,
>>> (0-5) is -5
True
Run Code Online (Sandbox Code Playgroud)
你能解释一下,为什么?也许这是某种错误或非常奇怪的行为.
> Python 2.7.3 (default, Apr 24 2012, 00:00:54) [GCC 4.7.0 20120414 (prerelease)] on linux2
>>> type(0-6)
<type 'int'>
>>> type(-6)
<type 'int'>
>>> type((0-6) is -6)
<type 'bool'>
>>>
Run Code Online (Sandbox Code Playgroud) 受这个关于缓存小整数和字符串的问题的启发,我发现了以下我不理解的行为.
>>> 1000 is 10**3
False
Run Code Online (Sandbox Code Playgroud)
我以为我理解了这种行为:1000是很大的缓存.1000和10**3指向2个不同的对象.但我错了:
>>> 1000 is 1000
True
Run Code Online (Sandbox Code Playgroud)
因此,Python可能会将计算与"正常"整数区别对待.但这种假设也是不正确的:
>>> 1 is 1**2
True
Run Code Online (Sandbox Code Playgroud)
如何解释这种行为?