比较运算符如何<和 &gt;将函数用作操作数? [英] How do comparison operators &lt; and &gt; work with a function as an operand?

查看:45
本文介绍了比较运算符如何<和 &gt;将函数用作操作数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遇到这个问题(在 Python 2.7.5 中),有一个小错误:

def foo(): 返回 3如果 foo >8:发射_the_nukes()

该死,我不小心炸开了月球.

我的理解是 E >F 等效于 (E).__gt__(F) 并且对于行为良好的类(例如内置函数)等效于 (F).__lt__(E).

如果没有 __lt____gt__ 运算符,那么我认为 Python 使用 __cmp__.

但是,这些方法都不适用于 function 对象,而 <> 运算符 do工作.到底是什么让这一切发生了?

<预><代码>>>>富>9e9真的>>>(foo).__gt__(9e9)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'function' 对象没有属性 '__gt__'>>>(9e9).__lt__(foo)未实现

解决方案

但是,这些方法都不适用于函数对象,而 <和 > 操作符确实有效.到底是什么让这一切发生了?

在默认情况下,2.x 系列中的 CPython 会根据类型名称进行任何其他合理的比较.(这是记录为实现细节,尽管有一些有趣的例外只能在在源代码中.)在 3.x 系列中,这将导致例外.

Python 规范对 2.x 中的行为设置了一些特定的约束;按类型名称进行比较不是唯一允许的行为,其他实现可能会做其他事情.不是什么可以依赖的东西.

Ran into this problem (in Python 2.7.5) with a little typo:

def foo(): return 3
if foo > 8:
    launch_the_nukes()

Dang it, I accidentally exploded the Moon.

My understanding is that E > F is equivalent to (E).__gt__(F) and for well behaved classes (such as builtins) equivalent to (F).__lt__(E).

If there's no __lt__ or __gt__ operators then I think Python uses __cmp__.

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?

>>> 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?

In default of any other sensible comparison, CPython in the 2.x series compares based on type name. (This is documented as an implementation detail, although there are some interesting exceptions which can only be found in the source.) In the 3.x series this will result in an exception.

The Python spec places some specific constraint on the behaviour in 2.x; comparison by type name is not the only permitted behaviour, and other implementations may do something else. It is not something to be relied on.

这篇关于比较运算符如何<和 &gt;将函数用作操作数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆