为什么整数在 python 2 中缺少一些特殊方法?

Why are integers missing some special methods in python 2?

在 python 2 或 3 中内置 类 有明确定义的特殊方法。 Explicit is better than implicit 和所有爵士乐。

5. > 4.
# True
(5.).__ge__(4.)
# True

但在 python2 中,某些方法存在例外情况,至少在整数方面是这样。

5 > 4
# True
(5).__ge__(4)
# AttributeError: 'int' object has no attribute '__ge__'
# But not all of them fail!
(5).__add__(4)
# 9

这种行为背后的原因是什么?为什么要这样设计?

我正在使用 Python 2.7.12

data model has been updated between and . In one could use the __cmp__ method:

object.__cmp__(self, other)

Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other. If no __cmp__(), __eq__() or __ne__() operation is defined, class instances are compared by object identity ("address"). See also the description of __hash__() for some important notes on creating hashable objects which support custom comparison operations and are usable as dictionary keys. (Note: the restriction that exceptions are not propagated by __cmp__() has been removed since Python 1.5.)

(已添加格式)

rich comparison 运算符是 __le__, __ge__, etc.. So in 还有一个 附加回退机制 。这是为 int 定义的,如您所见:

>>> (2).__cmp__
<method-wrapper '__cmp__' of int object at 0x13ee140>
>>> (2).__cmp__(3)
-1

(Python 2.7.12)

此外 offers a cmp(..) builtin function:

cmp(x, y)

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

(已添加格式)

, the __cmp__ has been removed as you can read in the What’s New In Python 3.0中:

The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)

(已添加格式)

此机制不仅仅是 __cmp__ 的包装器:它会首先查看是否存在 丰富的比较 ,如果没有则回退到 __cmp__ 本身。