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

前端 未结 3 1032
半阙折子戏
半阙折子戏 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 07:58

    Note: this only works in Python 2.x. In Python 3.x, it gives "TypeError: '(comparison operator)' not supported between instances of 'function' and 'int'".

    In Python 2.x, functions are more than infinitely large. For example, in Python 2.7.16 (repl.it), type this:

    > def func():
    ...    return 0
    ...
    > print(func)
    
    > int(func)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: int() argument must be a string or a number, not 'function'
    > id(func)
    IDNUMBER
    > x=id(func)
    > func func==x
    False
    > inf=float("inf")
    > func

    This shows that 'func' is greater than positive infinity in Python 2.x. Try this in Python 3.8.2 (repl.it):

    > def func():
    ...    return 0
    ...
    > func<10
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: '<' not supported between instances of 'function' and 'int'
    

    This shows that comparing with a function as an operand is only supported in Python 2.x, and that when comparing a function in Python 2.x, it is greater than Python's infinity. I hope this helped you!

提交回复
热议问题