2010-07-15 164 views
186

我最近遇到这个语法,我不知道其中的差别。“is None”和“== None”之间的区别是什么

如果有人能告诉我不同​​之处,我将不胜感激。

+2

看你错误[有间'=='和'is' Python中的区别吗?] (http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python/134659#134659) – 2010-07-15 16:58:50

+0

@ myusuf3:你可能想考虑改变接受的答案正确的一个。 – max 2012-01-24 19:12:18

回答

177

答案解释here

引述:

类是自由地实现 比较它选择的任何方式,它 可以选择让对 无对比意味着什么(这实际上 是有道理的,如果有人告诉你到 执行None对象从 从头开始,你会怎么得到它 比较自己?)。

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

+0

这是一个有趣的(和简短)阅读。还有一些有用的信息进入'is' v。'=='。 – 2010-07-15 16:59:58

+17

另外,'None'比'== None'快一点(〜50%):) – 2010-07-16 01:08:35

+0

@NasBanov你有链接到你读的地方吗? – myusuf3 2012-01-25 20:12:02

38

在这种情况下,它们是相同的。 None是一个单身物件(只存在一个None)。

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

例如:

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将返回true。

p = None 
q = None 
p is q # True because they are both pointing to the same "None" 
+14

这个答案不正确,正如Ben Hoffstein在http://stackoverflow.com/questions/3257919/is-none-vs-none/3257957#3257957下的回答所解释的那样。即使“x”不是“None”,“x == None”也可以评估为“True”,但是某些类的实例具有自己的自定义相等运算符。 – max 2010-11-16 03:00:04

91
class Foo: 
    def __eq__(self,other): 
     return True 
foo=Foo() 

print(foo==None) 
# True 

print(foo is None) 
# False 
3

如果使用numpy的,

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

会给时numpy的做的elementwise比较

相关问题