本文介绍了Python!=操作vs“不是"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对此问题的评论中,我看到了一条推荐使用

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“不是"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 16:45