Python无比较:我应该使用“is”或==? [英] Python None comparison: should I use "is" or ==?
问题描述
我使用的是Python 2.x。
当我比较 my_var == None
时,我的编辑器给我一个警告下划线,但是当我使用 my_var is None
。
我在Python shell中做了测试,并确定两者都是有效的语法,但我的编辑器似乎说 my_var是None
是优选的。
如果是这样,为什么?
摘要:
当您想要检查对象的身份时,使用例如检查
var
是无
)。当您想要检查相等时,使用 ==
(例如: var
等于<$
my_var == None
将返回 True
例如:
class Negator(object):
def __eq __(self,other):
return不是其他
thing = Negator()
print thing == None #True
print thing is None #False
是
检查对象身份。只有一个对象 None
,所以当你做 my_var是None
,你检查他们是否实际上是相同对象(不只是等效对象)
换句话说, ==
检查等价(从对象到对象定义),而是
检查对象身份:
lst = [1,2,3]
lst == lst [:]#这是真的,因为列表是等价的
lst is lst [:]#This是False,因为它们实际上是不同的对象
Possible Duplicate:
When is the `==` operator not equivalent to the `is` operator? (Python)
I am using Python 2.x.
My editor gives me a 'warning' underline when I compare my_var == None
, but no warning when I use my_var is None
.
I did a test in the Python shell and determined both are valid syntax, but my editor seems to be saying that my_var is None
is preferred.
Is this the case, and if so, why?
Summary:
Use is
when you want to check against an object's identity (e.g. checking to see if var
is None
). Use ==
when you want to check equality (e.g. Is var
equal to 3
?).
Explanation:
You can have custom classes where my_var == None
will return True
e.g:
class Negator(object):
def __eq__(self,other):
return not other
thing = Negator()
print thing == None #True
print thing is None #False
is
checks for object identity. There is only 1 object None
, so when you do my_var is None
, you're checking whether they actually are the same object (not just equivalent objects)
In other words, ==
is a check for equivalence (which is defined from object to object) whereas is
checks for object identity:
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
这篇关于Python无比较:我应该使用“is”或==?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!