作者:以真做假公馆 | 来源:互联网 | 2023-09-08 14:29
从python2manual:CPythonimplementationdetail:Objectsofdifferenttypesexceptnumbersar
从
python 2 manual:
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
当您订购两个字符串或两个数字类型时,排序是以预期的方式完成的(字符串的字典排序,整数的数字排序)。
当您订购数字和非数字类型时,数字类型优先。
>>> 5 <&#39;foo&#39;
True
>>> 5 <(1, 2)
True
>>> 5 <{}
True
>>> 5 <[1, 2]
True
当您订购两个不兼容的类型(两者都不是数字)时&#xff0c;它们按其类型名的字母顺序排序&#xff1a;
>>> [1, 2] > &#39;foo&#39; # &#39;list&#39; <&#39;str&#39;
False
>>> (1, 2) > &#39;foo&#39; # &#39;tuple&#39; > &#39;str&#39;
True
>>> class Foo(object): pass
>>> class Bar(object): pass
>>> Bar() True
一个例外是旧式类&#xff0c;它总是在新式类之前。
>>> class Foo: pass # old-style
>>> class Bar(object): pass # new-style
>>> Bar() False
Is this behavior mandated by the language spec, or is it up to implementors?
Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.
所以这是一个实现细节。
Are there differences between any of the major Python implementations?
我不能回答这一个&#xff0c;因为我只使用官方的CPython实现&#xff0c;但还有其他的Python实现&#xff0c;如PyPy。
Are there differences between versions of the Python language?
在Python 3.x中&#xff0c;行为已经改变&#xff0c;因此尝试排序整数和字符串将引发错误&#xff1a;
>>> &#39;10&#39; > 5
Traceback (most recent call last):
File "", line 1, in
&#39;10&#39; > 5
TypeError: unorderable types: str() > int()