Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> None > 0
False
>>> None == 0
False
>>> None < 0
True
- 是否使用为内置类型(在本例中为整数)明确定义的算术运算符比较
None
? - 是语言规范(Python 的规范 - 你一定是在开玩笑 :))的前两个和第三个比较部分之间的区别还是 CPython 的实现细节?
最佳答案
您可以真正与 None
一起使用的唯一有意义的比较是 if obj is None:
(或 if obj is not None:
)。
出于充分的理由,不同类型之间的比较已从 Python 3 中删除 - 它们是常见的错误来源并导致混淆。例如
>>> "3" < 4
False
在 Python 3 中,当比较不同类型的值(例如 str
与 int
或任何与 的值时,您会得到
。TypeError
无
>>> None < 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: NoneType() < int()
(我的意思是“比较”,意思是试图确定两个值中哪个更大/更小。比较相等是可以的 - 如果两个对象属于不同类型,它将始终返回 False
.)
我在文档中没有找到相关引用,但在 Learning Python, 4th edition , Mark Lutz 在第 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"
.
关于python - 使用算术运算符将 None 与内置类型进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8961005/