"是"运算符与整数意外行为 [英] "is" operator behaves unexpectedly with integers
问题描述
为什么以下在Python中出现意外行为?
Why does the following behave unexpectedly in 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之间的上述行为。
I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.
基于以上所述,我可以假设Python是内部的实现使得小整数以不同于大整数的方式存储,并且是
运算符可以区分。为什么泄漏抽象?当我不知道它们是否是数字时,比较两个任意对象以查看它们是否相同的更好的方法是什么?
Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the is
operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?
推荐答案
看看这个:
>>> a = 256
>>> b = 256
>>> id(a)
9987148
>>> id(b)
9987148
>>> a = 257
>>> b = 257
>>> id(a)
11662816
>>> id(b)
11662828
编辑:这是我在Python 2文档中找到的, 普通整数对象( Python 3 ):
Here's what I found in the Python 2 documentation, "Plain Integer Objects" (It's the same for Python 3):
当前实现为-5到256之间的所有
整数保留
整数对象数组,当你
在该范围内创建一个int
只需返回对现有对象
的引用。所以它应该是
可能改变值1. I
怀疑Python在
中的行为这种情况是未定义的。 : - )
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. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)
这篇关于"是"运算符与整数意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!