摘要: 使用is
时要核对对象的身份(如检查,看看是否var
是None
)。使用==
时要检查的平等(例如是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