相关疑难解决方法(0)

Python比较运算符<和>如何使用函数名作为操作数?

抛出这个问题(在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

16
推荐指数
1
解决办法
741
查看次数

在Python 2.x中,为什么函数和int之间支持>运算符?

在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定义+运算符,但<运算符是?

python int function operators python-2.x

5
推荐指数
1
解决办法
543
查看次数

标签 统计

python ×2

function ×1

int ×1

operators ×1

python-2.x ×1