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)
9987148
>>> id(b)
9987148
>>> a = 257
>>> b = 257
>>> id(a)
11662816
>>> id(b)
11662828

这是我在 "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.

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

相关文章:

python - 用于 Reed-Solomon 解码的 Berlekamp-Massey 勘误表(删除+错误)

java - 将非数字字符串转换为整数?

java - 为什么人们写--i?

python - 使用 Hough 变换、OpenCV 和 python 进行平行线检测

Python Mechanize 模块代理设置问题

python - 如何使用 Pyro 代理对象作为工厂?

java - 我想使2D随机数数组出现错误: incompatible types: int cannot be converted to int[]

java BufferedImage 到 int[] 问题

c++ - 为什么 'operator<<(cout, double)' 不起作用?

linux - bash 或 sh 中的 '=' 和 '==' 运算符之间有什么区别吗