问题:Python None比较:我应该使用“ is”还是==?

比较时我的编辑会警告我my_var == None,但使用时不会警告my_var is None

我在Python Shell中进行了测试,并确定两者都是有效的语法,但我的编辑器似乎在说这my_var is None是首选。

是这样吗?如果是这样,为什么?

My editor warns me 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?


回答 0

摘要:

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

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

回答 1

is通常,在将任意对象与单例对象进行比较时,通常首选,None因为它更快且更可预测。is总是按对象身份进行比较,而==做什么取决于操作数的确切类型,甚至取决于它们的顺序。

PEP 8对此建议提供了支持,该声明明确指出 “对单例的比较(如None,应始终使用isis not,绝不能使用相等运算符进行)”。

is is generally preferred when comparing arbitrary objects to singletons like None because it is faster and more predictable. is always compares by object identity, whereas what == will do depends on the exact type of the operands and even on their ordering.

This recommendation is supported by PEP 8, which explicitly states that “comparisons to singletons like None should always be done with is or is not, never the equality operators.”


回答 2

PEP 8定义is比较单例时最好使用运算符。

PEP 8 defines that it is better to use the is operator when comparing singletons.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。