作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
遇到这个问题(在 Python 2.7.5 中)有一点错别字:
def foo(): return 3
if foo > 8:
launch_the_nukes()
该死,我不小心把月球炸了。
我的理解是E > F
相当于(E).__gt__(F)
和行为良好的类(例如内置)相当于 (F).__lt__(E)
.
如果没有 __lt__
或 __gt__
运算符然后我认为 Python 使用 __cmp__
.
但是,这些方法都不适用于 function
<
时的对象和 >
运营商做工作。是什么让这一切发生?
>>> foo > 9e9
True
>>> (foo).__gt__(9e9)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__gt__'
>>> (9e9).__lt__(foo)
NotImplemented
最佳答案
But, none of these methods work with function objects while the < and > operators do work. What goes on under the hood that makes this happen?
在任何其他合理比较的默认情况下,2.x 系列中的 CPython 会根据类型名称进行比较。 (这是 documented as an implementation detail ,尽管有一些有趣的异常只能在 in the source 中找到。)在 3.x 系列中,这将导致异常。
Python 规范对 2.x 中的行为设置了一些特定的约束;按类型名称进行比较并不是唯一允许的行为,其他实现可能会做其他事情。这不是值得依赖的东西。
关于python - 比较运算符 < 和 > 如何将函数用作操作数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18387938/
我是一名优秀的程序员,十分优秀!