python - 使用算术运算符将 None 与内置类型进行比较?

标签 python comparison cpython

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 中,当比较不同类型的值(例如 strint 或任何与 的值时,您会得到 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/

相关文章:

c - 结构比较

python - 为什么要ing tuple(设置([1 ,"a","b","c","z","f"])== tuple(set(["a","b","c","z"0x1045610)

python - 获取 C-Python 中的类方法列表

python - 如何使用python通过正则表达式输出大写字母

python - BeautifulSoup 第一个元素不正确

Java - 在不同类型的对象上实现相等

python - 如何识别数学运算符

python - tkinter 选项菜单不显示选择

python - Flask,并非所有参数都在字符串格式化期间转换

algorithm - 图像比较(仅边缘/形状,无颜色)——如何区分猫和有猎物的猫