什么时候用 == 什么时候用 is? [英] When to use == and when to use is?

查看:59
本文介绍了什么时候用 == 什么时候用 is?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

奇怪:

<预><代码>>>>一 = 123>>>乙 = 123>>>a 是 b真的>>>a = 123.>>>b = 123.>>>a 是 b错误的

似乎a is b 或多或少被定义为id(a) == id(b).这样很容易产生错误:

basename, ext = os.path.splitext(fname)如果 ext 是.mp3":# 做一点事别的:# 做点别的

一些 fname 意外地出现在 else 块中.修复很简单,我们应该使用 ext == '.mp3' 代替,但是 if ext is '.mp3' 从表面上看似乎是一种很好的 Pythonic 方式写这个,它比正确"的方式更具可读性.

既然字符串是不可变的,那么为什么会出错的技术细节是什么?什么时候身份检查更好,什么时候平等检查更好?

解决方案

据我所知,is 检查对象身份等效性.由于没有强制的字符串驻留",两个刚好按顺序具有相同字符的字符串通常不是同一个字符串对象.

当您从字符串(或者实际上是序列中的任何子序列)中提取子字符串时,您最终会得到两个不同的对象,其中包含相同的值.

因此,当且仅当您比较对象身份时,才使用 is.比较值时使用 ==.

Curiously:

>>> a = 123
>>> b = 123
>>> a is b
True
>>> a = 123.
>>> b = 123.
>>> a is b
False

Seems a is b being more or less defined as id(a) == id(b). It is easy to make bugs this way:

basename, ext = os.path.splitext(fname)
if ext is '.mp3':
    # do something
else:
    # do something else

Some fnames unexpectedly ended up in the else block. The fix is simple, we should use ext == '.mp3' instead, but nonetheless if ext is '.mp3' on the surface seems like a nice pythonic way to write this and it's more readable than the "correct" way.

Since strings are immutable, what are the technical details of why it's wrong? When is an identity check better, and when is an equality check better?

解决方案

As far as I can tell, is checks for object identity equivalence. As there's no compulsory "string interning", two strings that just happen to have the same characters in sequence are, typically, not the same string object.

When you extract a substring from a string (or, really, any subsequence from a sequence), you will end up with two different objects, containing the same value(s).

So, use is when and only when you are comparing object identities. Use == when comparing values.

这篇关于什么时候用 == 什么时候用 is?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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