抛出这个问题(在Python 2.7.5中)有一点错字:
def foo(): return 3
if foo > 8:
launch_the_nukes()
Run Code Online (Sandbox Code Playgroud)
当它,我不小心爆炸了月亮.
我的理解是,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
Run Code Online (Sandbox Code Playgroud) 在Python 2.x中,以下代码产生错误,如预期的那样:
>>> def a(x): return x+3
...
>>> a+4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'function' and 'int'
Run Code Online (Sandbox Code Playgroud)
但是,允许以下内容:
>>> a < 4
False
Run Code Online (Sandbox Code Playgroud)
为什么没有为function和int定义+运算符,但<运算符是?