摘要:
使用
is时要核对对象的身份(如检查,看看是否
var是
None)。使用
==时要检查的平等(例如是
var等于
3?)。
说明:
你可以在其中
my_var == None返回的自定义类True
例如:
class Negator(object): def __eq__(self,other): return not otherthing = Negator()print thing == None #Trueprint 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



