在对此问题的评论中,我看到了一条建议使用的声明result is not None与result != None我想知道两者之间的区别是什么,为什么要推荐一个而不是另一个?
3 回答

红糖糍粑
TA贡献1815条经验 获得超6个赞
==
是一项平等测试。它检查右侧和左侧是否是相等的对象(根据它们__eq__
或__cmp__
方法)。
is
是身份测试。它检查右侧和左侧是否是同一对象。没有方法调用完成,对象不能影响is
操作。
您将is
(和is not
)用于单例,例如None
,您不在乎可能假装为的对象,None
或者在与之比较时要防止对象破裂的地方None
。

幕布斯7119047
TA贡献1794条经验 获得超8个赞
考虑以下:
class Bad(object):
def __eq__(self, other):
return True
c = Bad()
c is None # False, equivalent to id(c) == id(None)
c == None # True, equivalent to c.__eq__(None)
添加回答
举报
0/150
提交
取消