python - 为什么 collections.OrderedDict 使用 try 和 except 来初始化变量?

标签 python python-2.7 python-internals

下面是Python 2.7 中collections 模块的源代码。我对 OrderedDict 初始化其 __root 变量的方式感到困惑。为什么要用tryexcept,有必要吗?为什么它不能只使用

self.__root = root = []                     # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds) 

初始化self.__root

非常感谢...

class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.

# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three:  [PREV, NEXT, KEY].
def __init__(self, *args, **kwds):
    '''Initialize an ordered dictionary.  The signature is the same as
    regular dictionaries, but keyword arguments are not recommended because
    their insertion order is arbitrary.
    '''
    if len(args) > 1:
        raise TypeError('expected at most 1 arguments, got %d' % len(args))
    try:
        self.__root
    except AttributeError:
        self.__root = root = []                     # sentinel node
        root[:] = [root, root, None]
        self.__map = {}
    self.__update(*args, **kwds)

最佳答案

我找到了一个讨论 here (值得注意的是,Raymond Hettinger 是一名 Python 核心开发人员)。

从本质上讲,这似乎是针对用户第二次调用 __init__(而不是 update)的情况的预防措施,如下所示:

In [1]: from collections import OrderedDict

In [2]: od = OrderedDict([(1,2), (3,4)])

In [3]: od
Out[3]: OrderedDict([(1, 2), (3, 4)])

In [4]: od.__init__([(5,6), (7,8)])

In [5]: od
Out[5]: OrderedDict([(1, 2), (3, 4), (5, 6), (7, 8)])

虽然非常不常见,但这主要是为了与 dict.__init__ 保持一致,它也可以被第二次调用而不是 dict.update:

In [6]: d = {1:2, 3:4}

In [7]: d.__init__([(5,6), (7,8)])

In [8]: d
Out[8]: {1: 2, 3: 4, 5: 6, 7: 8}  # warning: don't rely on this order!

关于python - 为什么 collections.OrderedDict 使用 try 和 except 来初始化变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30704874/

相关文章:

python - Python如何知道已经存储在其内存中的值?

python - 添加既改变行为又存储参数的选项

python - 向程序添加子图会改变直方图的显示方式

python - 如何在 python 中将 <None> 类型对象的输出重定向到文本文件?

python - int() 对象如何在 python2 中使用没有 __eq__() 方法的 "=="运算符?

python - 为什么集合对象存储为卡住集而列表对象存储为元组?

Python:如果在另一个列表中找到该值,如何将字典中的值附加到列表

Python3 - 'Lock wait timeout exceeded; try restarting transaction' 并且只处理数据库

python - "if"带有接受 int 和 string 的输入的语句

python - 使用 Python 3 打印不带括号的不同错误消息