Python-将长/整数值与==和进行比较 [英] Python - comparing long/integer values with == and is

查看:66
本文介绍了Python-将长/整数值与==和进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python是

昨晚在某处发生了奇怪的变化

Ran into something odd last night where doing

if max_urls is 0:
    max_urls = 10

总是返回false ...即使max_urls为0...。当我做完

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

print type(max_urls)

会返回

<type 'long'> 0

这看似正确,但始终返回false。

which seemed right but it would always return false.

如果我将其更改为

if max_urls == 0:
    max_urls = 10

然后最终它在0时将返回true。为什么==和is之间的差异?

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

推荐答案

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

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

下面是一个简短的示例,说明了这一点:

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)

这篇关于Python-将长/整数值与==和进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆