gpt4 book ai didi

python - 比较运算符 < 和 > 如何将函数用作操作数?

转载 作者:太空狗 更新时间:2023-10-29 16:57:01 26 4
gpt4 key购买 nike

遇到这个问题(在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com