How do comparison operators < and> work with a function as an operand?

前端 未结 3 1046
半阙折子戏
半阙折子戏 2020-11-30 07:16

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 accidental

3条回答
  •  爱一瞬间的悲伤
    2020-11-30 08:00

    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.

提交回复
热议问题