问题描述
在对此问题的评论中,我看到了一条推荐使用
In a comment on this question, I saw a statement that recommended using
result is not None
vs
result != None
我想知道两者之间有什么区别,为什么可能要推荐一个而不是另一个?
I was wondering what the difference is, and why one might be recommended over the other?
推荐答案
==
是平等性测试.它检查右侧和左侧是否相等(根据它们的__eq__
或__cmp__
方法).
==
is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their __eq__
or __cmp__
methods.)
is
是身份测试.它检查右侧和左侧是否是同一对象.没有方法调用完成,对象不能影响is
操作.
is
is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the is
operation.
您将is
(和is not
)用于单例,例如None
,在这里您不关心可能假装为None
的对象,或者在出现以下情况时防止对象破裂的地方:与None
进行比较.
You use is
(and is not
) for singletons, like None
, where you don't care about objects that might want to pretend to be None
or where you want to protect against objects breaking when being compared against None
.
这篇关于Python!=操作vs“不是"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!