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

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

问题描述

好奇地:

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

似乎a is b或多或少地定义为id(a) == id(b).用这种方法很容易产生错误:

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

某些fname意外地以else块结尾.修复很简单,我们应该改用ext == '.mp3',但是表面上的if ext is '.mp3'似乎是一种不错的pythonic方式来编写此代码,并且比正确"的方法更具可读性.

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?

推荐答案

据我所知,is检查对象身份等效性.由于没有强制性的字符串插入",所以两个碰巧顺序上具有相同字符的字符串通常不是相同的字符串对象.

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).

因此,仅在比较对象标识时才使用is.比较值时,请使用==.

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

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

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