Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...