对对象强加任意顺序。顺序仅定义为在程序执行过程中稳定 http://docs.python.org/2/reference/expressions.html#not-in.
这意味着在比较任意对象时,由 Python 实现来定义顺序。如果类型相同(来自C source http://hg.python.org/cpython/file/23ebb8936bf6/Objects/object.c#l756):
if (v->ob_type == w->ob_type) {
/* When comparing these pointers, they must be cast to
* integer types (i.e. Py_uintptr_t, our spelling of C9X's
* uintptr_t). ANSI specifies that pointer compares other
* than == and != to non-related structures are undefined.
*/
Py_uintptr_t vv = (Py_uintptr_t)v;
Py_uintptr_t ww = (Py_uintptr_t)w;
return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
}
相同的值是基础id()
函数,并且也在默认值中表示repr()
自定义类的字符串,所以它可能appear认为repr()
类的数量决定顺序。这只是内存地址的作用。
对于以下对象not同一类型,同一类型name而是使用(类似数字的类型在其他类型之前排序),并且如果类型不同但它们的类型不同names相同时,代码会回退到类型的内存地址(与类型相同时实例的内存地址相反)。
这种隐式排序被认为是语言中的错误,并且已被在 Python 3 中修复 http://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons:
排序比较运算符 (<
, <=
, >=
, >
)提出一个TypeError
当操作数没有有意义的自然顺序时例外。
这适用于未实现必要的自定义类订购挂钩 http://docs.python.org/3/reference/datamodel.html#object.__lt__:
>>> class Foo(): pass
...
>>> Foo() < Foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: Foo() < Foo()