如何在OrderedDict中访问__map?

时间:2018-12-19 12:19:17

标签: python

我查看了source code中的OrderedDict,它具有以下内容:

def __setitem__(self, key, value,
                    dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
        'od.__setitem__(i, y) <==> od[i]=y'
        # Setting a new item creates a new link at the end of the linked list,
        # and the inherited dictionary is updated with the new key/value pair.
        if key not in self:
            self.__map[key] = link = Link()
            root = self.__root
            last = root.prev
            link.prev, link.next, link.key = last, root, key
            last.next = link
            root.prev = proxy(link)
        dict_setitem(self, key, value)

我想看看OrderedDict内部的__map对象,但是当我在OrderedDict对象上运行dir()时,输出中没有__map对象。实际上,__dict__属性为空:

>>> from collections import OrderedDict
>>> a = OrderedDict()
>>> a[1] = 1
>>> a
OrderedDict([(1, 1)])
>>> dir(a)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'move_to_end', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> a.__dict__
{}
>>> a.__map
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'collections.OrderedDict' object has no attribute '__map'

所以,确实有2个问题。

  1. 为什么__map属性(以及__root和其他属性)没有显示在dir()中

  2. 访问__map属性必须做什么?

编辑:我也尝试过改名:

>>> a._OrderedDict__map
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'collections.OrderedDict' object has no attribute '_OrderedDict__map'

0 个答案:

没有答案