本文翻译自:What is the difference between “ is None ” and “ ==None ”
I recently came across this syntax, I am unaware of the difference. 我最近遇到了这种语法,我不知道有什么区别。
I would appreciate it if someone could tell me the difference. 如果有人可以告诉我与众不同,我将不胜感激。
#1楼
参考:https://stackoom.com/question/dFx5/is-None-和-None-有什么区别
#2楼
If you use numpy, 如果您使用numpy,
if np.zeros(3)==None: pass
will give you error when numpy does elementwise comparison numpy进行元素比较时会给你错误
#3楼
In this case, they are the same. 在这种情况下,它们是相同的。 None
is a singleton object (there only ever exists one None
). None
是一个单例对象(只有一个None
存在)。
is
checks to see if the object is the same object, while == just checks if they are equivalent. is
检查对象是否为同一对象,而==仅检查它们是否等效。
For example: 例如:
p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent
But since there is only one None
, they will always be the same, and is
will return True. 但由于只有一个None
,他们永远是相同的,并且is
将返回true。
p = None
q = None
p is q # True because they are both pointing to the same "None"
#4楼
The answer is explained here . 答案在这里解释。
To quote: 报价:
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?). 一个类可以自由选择以任何方式实现比较,并且可以选择与None进行比较意味着某种意义(这实际上是有道理的;如果有人告诉您从头开始实现None对象,那么您将如何获得它来比较True?反对自己?)。
Practically-speaking, there is not much difference since custom comparison operators are rare. 实际上,由于自定义比较运算符很少见,因此差异不大。 But you should use is None
as a general rule. 但是您应该使用is None
作为一般规则。
#5楼
class Foo:
def __eq__(self,other):
return True
foo=Foo()
print(foo==None)
# True
print(foo is None)
# False