来自蟒蛇2手册 http://docs.python.org/2/library/stdtypes.html#comparisons:
CPython实现细节:除数字之外的不同类型的对象按其类型名称排序;不支持正确比较的相同类型的对象按其地址排序。
当您对两个字符串或两个数字类型进行排序时,排序将以预期的方式完成(字符串的字典顺序,整数的数字顺序)。
当您订购数字类型和非数字类型时,数字类型排在第一位。
>>> 5 < 'foo'
True
>>> 5 < (1, 2)
True
>>> 5 < {}
True
>>> 5 < [1, 2]
True
当您对两个都不是数字的不兼容类型进行排序时,它们将按类型名称的字母顺序排序:
>>> [1, 2] > 'foo' # 'list' < 'str'
False
>>> (1, 2) > 'foo' # 'tuple' > 'str'
True
>>> class Foo(object): pass
>>> class Bar(object): pass
>>> Bar() < Foo()
True
一个例外是旧式类总是出现在新式类之前。
>>> class Foo: pass # old-style
>>> class Bar(object): pass # new-style
>>> Bar() < Foo()
False
这种行为是由语言规范强制执行的,还是由实现者决定?
有无语言规范 https://stackoverflow.com/questions/1094961/is-there-a-python-language-specification. The 语言参考 https://docs.python.org/2/reference/expressions.html#value-comparisons says:
否则,不同类型的对象总是比较不相等,并且顺序一致但任意。
所以这是一个实现细节。
主要 Python 实现之间是否存在差异?
我无法回答这个问题,因为我只使用了官方的 CPython 实现,但还有其他 Python 实现,例如 PyPy。
Python 语言的版本之间有差异吗?
在 Python 3.x 中,行为已更改,因此尝试对整数和字符串进行排序将引发错误:
>>> '10' > 5
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
'10' > 5
TypeError: unorderable types: str() > int()