我正在尝试编写一个使用python 2.7.10从OrderedDict继承的python类。

最基本的类如下所示:

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原生的。

最佳答案

您忘记了初始化基类。在您的代码中,__init__仅初始化Game元素,而无法初始化基础的OrderedDict。您必须显式调用基类__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表示形式。

关于python - Python 2.7:具有OrderedDict属性错误的继承<myclass>类没有属性'_OrderedDict__root',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51946149/

10-13 08:03