使用算术运算符将 None 与内置类型进行比较?
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 的实现细节?
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
- Is comparing
None
using arithmetic operators well defined for built-in types (integers in this case)? - Is the difference between the first two and the third comparison part of language specification (Python's specification - you must be kidding :)) or is it CPython's implementation detail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
真正可以与
None
进行比较的唯一有意义的比较是if obj is None:
(或if obj is not None:
)。不同类型之间的比较已从 Python 3 中删除,原因很充分——它们是错误的常见来源并导致混乱。例如
,在 Python 3 中,当比较不同类型的值(例如
str
与int
或任何内容与None)时,您会收到
。TypeError
错误(我的意思是“比较”,试图确定两个值中哪一个更大/更小。比较相等性是可以的 - 如果两个对象属于不同类型,它总是返回 False。
)尚未在文档中找到这方面的参考资料,但在 学习 Python,第四版 中,Mark Lutz 写道第 204 页:
The only meaningful comparison you can really use with
None
isif obj is None:
(orif obj is not None:
).Comparison between different types has been removed from Python 3 for good reasons - they were a common source of errors and lead to confusion. For example
In Python 3, you get a
TypeError
when comparing values of different types likestr
vs.int
or anything vs.None
.(I mean "comparing" in the sense of trying to determine which of two values is larger/smaller. Comparison for equality is OK - it will always return
False
if two object are of different types.)I haven't found a reference in the docs for this, but in Learning Python, 4th edition, Mark Lutz writes on page 204:
来自 http://bytes.com/topic/python 的一些有趣的引用/answers/801701-why-none-0-a
和
Some interesting quotes from http://bytes.com/topic/python/answers/801701-why-none-0-a
and