Python 2.7: inheritance with OrderedDict 属性错误 <myclass> class has no attribute '_OrderedDict__root'

Python 2.7: inheritance with OrderedDict Attribute error <myclass> class has no attribute '_OrderedDict__root'

我正在尝试使用 python 2.7.10.

编写一个继承自 OrderedDict 的 python class

最基本的 class 看起来像这样:

from collections import OrderedDict

class Game (OrderedDict):

  def __init__(self,theTitle="",theScore=0):
    self['title'] = theTitle
    self['score'] = theScore


  def __str__(self):
    return "hi"
    #return 'title: ' + self['title'] + ", score:" + str(self['score'])

当我 运行 它时,我得到这个错误:

 (metacrit) Jasons-MBP:mc jtan$ python
Python 2.7.10 (default, Oct  6 2017, 22:29:07) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from game import Game
>>> g = Game('battlezone',100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "game.py", line 7, in __init__
    self['title'] = theTitle
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 64, in __setitem__
    root = self.__root
AttributeError: 'Game' object has no attribute '_OrderedDict__root'
>>>

谁能告诉我我做错了什么? 我很确定 OrderedDict 在这个版本的 Python 中,这是我第一件事,但还不确定去哪里。 我还不是 python 本地人。

您忘记初始化基础 class。在您的代码中,__init__ 仅初始化 Game 元素而无法初始化基础 OrderedDict。您必须显式调用基础 class __init__ 方法:

class Game (OrderedDict):

  def __init__(self,theTitle="",theScore=0):
    OrderedDict.__init__(self)    
    self['title'] = theTitle
    self['score'] = theScore


  def __str__(self):
    return "hi"
    #return 'title: ' + self['title'] + ", score:" + str(self['score'])

然后就可以成功了:

>>> g = Game('battlezone',100)
>>> g
Game([('title', 'battlezone'), ('score', 100)])
>>> str(g)
'hi'

由于__repr__没有被覆盖,你可以看到OrderedDict的表示。