小编典典

Python None比较:我应该使用“ is”还是==?

python

我正在使用Python2.x。

比较时我的编辑会警告我my_var == None,但使用时不会警告my_var is None

我在Python Shell中进行了测试,并确定两者都是有效的语法,但我的编辑器似乎在说这my_var is None是首选。

是这样吗?如果是,为什么?


阅读 1420

收藏
2020-02-22

共1个答案

小编典典

摘要:
使用is时要核对对象的身份(如检查,看看是否varNone)。使用==时要检查的平等(例如是var等于3?)。

说明:
你可以在其中my_var == None返回的自定义类True

例如:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is检查对象身份。只有1个对象None,因此在执行操作时my_var is None,你要检查它们是否实际上是同一对象(而不仅仅是等效对象)

换句话说,==是检查等效性(定义在对象之间),而is检查对象身份:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects
2020-02-22