“ is None”和“ == None”有什么区别?

本文翻译自: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值