关于python:“is None”和“== None”之间的区别是什么?

What is the difference between “ is None ” and “ ==None ”

我最近遇到了这种语法,我不知道有什么不同。

如果有人能告诉我区别,我会很感激的。


答案在这里解释。

引用:

A class is free to implement
comparison any way it chooses, and it
can choose to make comparison against
None mean something (which actually
makes sense; if someone told you to
implement the None object from
scratch, how else would you get it to
compare True against itself?).

实际上,没有太大的区别,因为自定义比较运算符很少见。但是你应该使用is None作为一个一般规则。


1
2
3
4
5
6
7
8
9
10
class Foo:
    def __eq__(self,other):
        return True
foo=Foo()

print(foo==None)
# True

print(foo is None)
# False


在这种情况下,它们是相同的。None是一个单体对象(只有一个None存在)。

is检查对象是否是同一对象,而==只检查它们是否相等。

例如:

1
2
3
4
p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent

但是,由于只有一个None,它们总是相同的,is将返回真值。

1
2
3
p = None
q = None
p is q # True because they are both pointing to the same"None"


如果你用麻木,

1
if np.zeros(3)==None: pass

当numpy进行elementwise比较时会出错