KeyError: '_OrderedDict__root?

KeyError: '_OrderedDict__root?

您好,我有以下代码片段,它给出了 KeyError。我已经检查了其他指定 make __init__ call to Ordered Dict 的链接,我已经完成了。但是还是不行。

from collections import OrderedDict

class BaseExcelNode(OrderedDict):
    def __init__(self):
        super(BaseExcelNode, self).__init__()
        self.start_row = -1
        self.end_row = -1
        self.col_no = -1

    def __getattr__(self, name):
        return self[name]

    def __setattr__(self, name, value):
        self[name] = value
BaseExcelNode()

Error:

Traceback (most recent call last):
  File "CIMParser.py", line 29, in <module>
    BaseExcelNode()
  File "CIMParser.py", line 9, in __init__
    super(BaseExcelNode, self).__init__()
  File "C:\Python27\lib\collections.py", line 64, in __init__
    self.__root
  File "CIMParser.py", line 15, in __getattr__
    return self[name]
KeyError: '_OrderedDict__root'

OrderedDict 是在属性访问通过默认机制工作的假设下实现的,特别是,属性访问不等同于索引。

当您对其进行子类化并更改属性访问的工作方式时,您打破了 OrderedDict 实现的最深层假设之一,一切都会变得糟糕。

使用猴子补丁方法:

from collections import OrderedDict

class BaseExcelNode(OrderedDict):
    def __init__(self):
        super(BaseExcelNode, self).__init__()
        self.start_row = -1
        self.end_row = -1
        self.col_no = -1

    def __getattr__(self, name):
        if not name.startswith('_'):
            return self[name]
        super(BaseExcelNode, self).__getattr__(name)

    def __setattr__(self, name, value):
        if not name.startswith('_'):
            self[name] = value
        else:
            super(BaseExcelNode, self).__setattr__(name, value)

b = BaseExcelNode()