Python无比较:我应该使用“is”或==? [英] Python None comparison: should I use "is" or ==?

查看:161
本文介绍了Python无比较:我应该使用“is”或==?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


我使用的是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆