您真正可以使用None
的唯一有意义的比较是if obj is None:
(或if obj is not None:
)。
不同类型之间的比较已从Python 3中删除,原因很充分 - 它们是错误的常见来源,并导致混淆。例如
>>> "3" < 4
False
在Python 3,你比较不同类型的值时,像str
与int
或任何与None
得到TypeError
。
>>> None < 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: NoneType() < int()
(我的意思是在试图确定哪两个数值越大/小平等比较正常意义上的“比较” - 它总是返回False
如果两个对象是不同类型的。)
我没有找到的文档此的引用,但在Learning Python, 4th edition,马克·鲁茨204页上写道:
[...] Comparisons of differently typed objects (e.g., a string and a list) work — the language defines a fixed ordering among different types, which is deterministic, if not aesthetically pleasing. That is, the ordering is based on the names of the types involved: all integers are less than all strings, for example, because "int"
is less than "str"
.
'=='和'!='通常是安全的,但你应该使用'是None'和'不None'为单身如'None'按[PEP-8](http://www.python.org/dev/peps/pep-0008/) – ThiefMaster
@ThiefMaster问题的关键是*安全*在这里的含义。我很清楚应该使用'is'来比较'None',但问题是特定的,并且不会询问应该使用哪个运算符。 –
http://bugs.python.org/issue1673405 – wim