我在Python shell中做了一个测试,并确定两者都是有效的语法,但我的编辑器似乎说这my_var is None是首选。
是这种情况,如果是这样,为什么?
莫回无
浏览 517回答 3
3回答
翻过高山走不出你
摘要:使用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 #Falseis检查对象标识。只有一个对象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