相关疑难解决方法(0)

为什么(0-6)是-6 =假?

可能重复:
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)

python debugging integer cpython

129
推荐指数
4
解决办法
4897
查看次数

为什么Python处理'1是1**2'与'1000是10**3'不同?

这个关于缓存小整数和字符串的问题的启发,我发现了以下我不理解的行为.

>>> 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)

如何解释这种行为?

python reference python-internals semantics

26
推荐指数
1
解决办法
1519
查看次数