本文介绍了“foo is None"和“foo is None"之间有什么区别吗?和“foo == None"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么区别:
如果 foo 是 None:通过
和
if foo == None: pass
我在大多数 Python 代码(以及我自己编写的代码)中看到的约定是前者,但我最近遇到使用后者的代码.None 是 NoneType 的一个实例(也是唯一的实例,IIRC),所以它应该无关紧要,对吧?有没有可能发生的情况?
解决方案
is
如果比较同一个对象实例,总是返回 True
而 ==
最终由 __eq__()
方法决定
即
>>> 类 Foo(对象):def __eq__(自我,其他):返回真>>> f = Foo()>>> f == 无真的>>> f 是无错误的Is there any difference between:
if foo is None: pass
and
if foo == None: pass
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
解决方案
is
always returns True
if it compares the same object instance
Whereas ==
is ultimately determined by the __eq__()
method
i.e.
>>> class Foo(object):
def __eq__(self, other):
return True
>>> f = Foo()
>>> f == None
True
>>> f is None
False
这篇关于“foo is None"和“foo is None"之间有什么区别吗?和“foo == None"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!