在Python中为None [英] identity versus equality for None in Python
问题描述
各种Python指南说使用 x是无
而不是 x == None
。这是为什么?平等用于比较值,因此看来是否 x
具有值 None
,表示为 ==
而不是是
。有人可以解释为什么是
是首选表单,并显示一个示例,其中两个不给出相同的答案?
Various Python guides say to use x is None
instead of x == None
. Why is that? Equality is used for comparing values, so it seems natural to ask if x
has the value None
, denoted with ==
and not is
. Can someone explain why is
is the preferred form and show an example where the two do not give the same answer?
感谢。
推荐答案
人们使用是
是因为使用 ==
没有优势。可以编写比较等于 None
的对象,但不常见。
The reason people use is
is because there is no advantage to using ==
. It is possible to write objects that compare equal to None
, but it is uncommon.
class A(object):
def __eq__(self, other):
return True
print A() == None
输出:
True
是
不要认为这个事实很重要。
The is
operator is also faster, but I don't consider this fact important.
这篇关于在Python中为None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!