python - "is"运算符对整数的行为异常

标签 python int operators identity python-internals

为什么以下代码在 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

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

基于上述内容,我可以假设 Python 的内部实现方式是“小”整数的存储方式与大整数不同,并且 is 运算符可以区分两者。为什么会出现泄漏抽象?当我事先不知道它们是否是数字时,比较两个任意对象以查看它们是否相同的更好方法是什么?

最佳答案

看看这个:

>>> a = 256
>>> b = 256
>>> id(a) == id(b)
True
>>> a = 257
>>> b = 257
>>> id(a) == id(b)
False

这是我在 "Plain Integer Objects" 的文档中找到的内容:

The current implementation keeps an array of integer objects for all integers between -5 and 256. When you create an int in that range you actually just get back a reference to the existing object.

所以,整数 256 是 identical ,但 257 不是。这是 CPython 实现细节,不保证其他 Python 实现。

关于python - "is"运算符对整数的行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60386504/

相关文章:

python - 如何使用开罗将文本保持在一个圆圈内?

python - SSHCommandClientEndpoint,扭曲。如何执行多个命令?

c - 是否可以替换 double 并仅使用 C 中的整数编写程序,并具有相同的输出?

java - 在字符串数组中搜索字符串

java println ("a==b"+"is"+a==b) 打印 false 而不是 "a==b is true"

python - 使用正则表达式从 HTML 中提取所有值

objective-c - int 不增加

c++ - 类型结果之间的意外差异

php - 为什么 PHP 中的字符串连接使用句号 "."而不是加号 "+"?

python - SSL错误 : Not a directory