为什么 Python 2 中的类型顺序是固定的,而 Python 3 中的 TypeError 是不可排序的? [英] Why is the order of types in Python 2 fixed, and an unorderable TypeError in Python 3?

查看:34
本文介绍了为什么 Python 2 中的类型顺序是固定的,而 Python 3 中的 TypeError 是不可排序的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Question 1: Why is this order of types in Python 2 fixed?

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

True

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

Is this because of their id() in their lifetime?

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 内置的导入时间?在另一个 shell 中的结果相同:

Or, because of Python builtin import time? Same result in another shell:

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:

However tested it in Python 3, it will be a 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?

Question 2: why is this a TypeError in Python 3?

推荐答案

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

  1. Because that's how the developers of Python decided to do it. That order is hard-coded in the interpreter (for CPython at least; other implementations may do it differently). The idea was to have a list containing various data types sort in a consistent order.

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

Because the developers of Python decided they'd made a mistake with the Python 2.x behavior and decided that "explicit is better than implicit". Now you must provide a key function when sorting lists containing items of different types to make sure you get exactly what you want.

这篇关于为什么 Python 2 中的类型顺序是固定的,而 Python 3 中的 TypeError 是不可排序的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆