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

Bri*_*ton 5 python int function operators python-2.x

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

Mar*_*ers 13

在Python 2中,所有对象都是可订购的.

CPython(最初的Python实现)在数字之前命令None,然后在其他所有数字之前输入数字.没有自己实现排序的对象按类型名称进行比较; 所以function在课程实例之前进行排序Zippedeedoodah.其他实现可以自由选择不同的订单.

Python这样做是为了支持异构列表的排序.引用Comparisons表达式文档:

运营商<,>,==,>=,<=,和!=比较两个对象的值.对象不必具有相同的类型.如果两者都是数字,则将它们转换为通用类型.否则,不同类型的对象总是比较不相等,并且一致但是任意地排序.

在Python 3中,只支持明确支持排序的对象,其他一切都会引发异常:

>>> def a(x): return x+3 
... 
>>> a < 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: function() < int()
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

543 次

最近记录:

11 年,3 月 前