Python - 将长/整数值与 == 和 is 进行比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4473673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:53:26  来源:igfitidea点击:

Python - comparing long/integer values with == and is

pythonvariablesconditional-operator

提问by Wizzard

Possible Duplicate:
Python “is” operator behaves unexpectedly with integers

可能的重复:
Python“is”运算符对整数的行为出乎意料

Ran into something odd last night where doing

昨晚在做什么时遇到了一些奇怪的事情

if max_urls is 0:
    max_urls = 10

would always return false... even when max_urls was 0.... it was getting assigned from the database. When I did a

总是会返回 false... 即使 max_urls 为 0 .... 它是从数据库中分配的。当我做了一个

print type(max_urls)

would return

会回来

<type 'long'> 0

which seemed right but it would always return false.

这似乎是正确的,但它总是会返回 false。

If I changed it to

如果我把它改成

if max_urls == 0:
    max_urls = 10

then finally it would return true when it was 0. Why the difference between == and is?

那么最终它会在为 0 时返回 true。为什么 == 和 is 之间的区别?

回答by Andrew Clark

==is a value comparison, isis an object identity (memory location) comparison. You will often see that comparisons like max_urls is 0will give the intended result because small values are usuallycached in Python, but you always want to be using ==instead of iswhen checking equality because this behavior cannot be relied upon.

==是值比较,is是对象标识(内存位置)比较。你会经常看到,像这样的比较max_urls is 0会给出预期的结果,因为小值通常被缓存在 Python 中,但你总是希望使用==而不是is在检查相等性时使用,因为不能依赖这种行为。

Here is a brief example illustrating this:

下面是一个简单的例子来说明这一点:

>>> a = 0
>>> (a == 0, a is 0)
(True, True)
>>> a = 1000
>>> (a == 1000, a is 1000)
(True, False)

回答by John Kugelman

The isoperator checks that two references point to the same object. You are testing if long(0)is the same object as int(0), and the answer is no. This will be crystal clear if you print their object ids:

is运营商将检查两个引用指向同一个对象。您正在测试 iflong(0)是否与 相同int(0),答案是否定的。如果您打印它们的对象 ID,这将非常清楚:

>>> max_urls = long(0)
>>> id(max_urls)
335952
>>> id(0)
8402324

==on the other hand checks that two values are equivalent, even if they are not the exact same object. For instance:

==另一方面,检查两个值是否相等,即使它们不是完全相同的对象。例如:

>>> a = 777
>>> b = 777
>>> a is b
False
>>> a == b
True
>>> id(a)
8404568
>>> id(b)
8404640

Note:It is important that I used 777 and not a smaller number like 1 or 2. Quoting from the Python manual:

注意:重要的是我使用了 777 而不是更小的数字,比如 1 或 2。引自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.

当前的实现为 -5 到 256 之间的所有整数保留了一个整数对象数组,当您在该范围内创建一个 int 时,您实际上只是返回对现有对象的引用。