为什么 Python 2 中的类型顺序是固定的,而在 Python 3 中是不可排序的 TypeError



问题1:为什么Python 2中的类型顺序是固定的?

object > type > tuple > (bytes or str) > frozenset > set > dict 
       > long > list > int > float > complex > bytearray > None
True

这是因为他们一生中的id()吗?

for t in types:
    print repr(t), id(t)
<type 'object'> 4439116416
<type 'type'> 4439115752
<type 'tuple'> 4439113712
<type 'str'> 4439103312
<type 'frozenset'> 4439096880
<type 'set'> 4439095648
<type 'dict'> 4439083728
<type 'long'> 4439081736
<type 'list'> 4439076128
<type 'int'> 4439074040
<type 'float'> 4439065096
<type 'complex'> 4439029656
<type 'bytearray'> 4439016144
None 4439091192

或者,因为 Python 内置导入时间?在另一个外壳中产生相同的结果:

Python 2.7.9 (default, Jan 29 2015, 06:27:40)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> object > type > tuple > (bytes or str) > frozenset > set > dict > long > list > int > float > complex > bytearray > None
True

然而,在Python 3中对其进行了测试,它将是一个TypeError

Python 3.4.3 (default, Feb 25 2015, 21:28:45)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> object > type > tuple > (bytes or str) > frozenset > set > dict > long > list > int > float > complex > bytearray > None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: type() > type()

问题 2:为什么这是 Python 3 中的TypeError

  1. 因为这就是Python的开发人员决定这样做的方式。该顺序在解释器中是硬编码的(至少对于CPython;其他实现可能会以不同的方式进行)。这个想法是让一个包含各种数据类型的列表按一致的顺序排序。

  2. 因为Python的开发人员认为他们在Python 2.x行为上犯了一个错误,并决定"显式优于隐式"。现在,在对包含不同类型项目的列表进行排序时,您必须提供一个key函数,以确保您得到所需的内容。

相关内容

最新更新