相关疑难解决方法(0)

"是"运算符与整数意外行为

为什么以下在Python中出现意外行为?

>>> a = 256
>>> b = 256
>>> a is b
True           # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False          # What happened here? Why is this False?
>>> 257 is 257
True           # Yet the literal numbers compare properly
Run Code Online (Sandbox Code Playgroud)

我使用的是Python 2.5.2.尝试一些不同版本的Python,似乎Python 2.3.3显示了99到100之间的上述行为.

基于以上所述,我可以假设Python在内部实现,使得"小"整数以不同于大整数的方式存储,is运算符可以区分.为什么泄漏抽象?当我不知道它们是否是数字时,比较两个任意对象以查看它们是否相同的更好的方法是什么?

python int identity operators python-internals

476
推荐指数
11
解决办法
6万
查看次数

python'不是'运营商

我注意到有一个比较运算符is not.我应该把它翻译成

!= 
Run Code Online (Sandbox Code Playgroud)

代替

== not
Run Code Online (Sandbox Code Playgroud)

python

44
推荐指数
3
解决办法
6万
查看次数

标签 统计

python ×2

identity ×1

int ×1

operators ×1

python-internals ×1