tao*_*.li 5 python python-2.7 python-internals
下面是collectionsPython 2.7中模块的源代码.我对OrderedDict初始化__root变量的方式感到困惑.为什么使用它try和except,有必要吗?为什么不能只使用它
self.__root = root = [] # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds)
Run Code Online (Sandbox Code Playgroud)
初始化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)
Run Code Online (Sandbox Code Playgroud)
我在这里找到了一个讨论(值得注意的是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)])
Run Code Online (Sandbox Code Playgroud)
虽然非常罕见,但这对于一致性来说非常重要,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!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
431 次 |
| 最近记录: |