相关疑难解决方法(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!=操作vs"不是"

在对这个问题的评论中,我看到了一个建议使用的声明

result is not None
Run Code Online (Sandbox Code Playgroud)

VS

result != None
Run Code Online (Sandbox Code Playgroud)

我想知道区别是什么,以及为什么可能推荐另一个?

python operators

223
推荐指数
5
解决办法
16万
查看次数

标签 统计

operators ×2

python ×2

identity ×1

int ×1

python-internals ×1