【问题标题】:python TypeError: object does not support indexingpython TypeError:对象不支持索引
【发布时间】:2012-03-17 06:36:51
【问题描述】:

这是我的代码的错误部分:

class Room(object):
    def __init__(self):
        self.hotspots = []
        self.image = []
        self.item = []

    def newhotspot(*args):
        new = {'Name' : None,
               'id' : None,
               'rect' : None,
               'Takeable' : None,
               'Lookable' : None,
               'Speakable' : None,
               'Itemable' : None,
               'Goable' : None}

        for i in args:
            new[i[0]] = i[1]
        new['id'] = len(self.hotspots)
        self.hotspots.append(new)

CityTrader = Room()

CityTrader.newhotspot(('Name', 'Trader'),
                      ('Takeable', 'Yes'))

目标是有一个字典,除了指定的键之外,所有键都设置为无。 但是,当我运行它时,我得到:

[...]line 85 in <module>
('Takeable', 'Yes'))
[...]line 44, in newhotspot
new[i[0]] = i[1]
TypeError : 'Room' object does not support indexing

有人知道为什么以及如何解决这个问题吗? 当它没有被包裹在一个类中时,它似乎可以工作。

【问题讨论】:

    标签: python typeerror


    【解决方案1】:

    你忘记了self参数到newhotspot()

    def newhotspot(self, *args):
        ...
    

    由于self 无论如何都会被隐式传递,它最终成为args 的第一项。

    【讨论】:

      【解决方案2】:

      每个类方法都必须将 self 作为它的第一个参数。

      试试这个:

      class Room(object):
          def __init__(self):
              self.hotspots = []
              self.image = []
              self.item = []
      
          def newhotspot(self, *args):
             new = {'Name' : None,
             'id' : None,
             'rect' : None,
             'Takeable' : None,
             'Lookable' : None,
             'Speakable' : None,
             'Itemable' : None,
             'Goable' : None}
      
             for i in args:
                 new[i[0]] = i[1]
             new['id'] = len(self.hotspots)
             self.hotspots.append(new)
      
      CityTrader = Room()
      
      CityTrader.newhotspot(('Name', 'Trader'),
                            ('Takeable', 'Yes'))
      

      【讨论】:

      • 错误,类方法将类作为第一个参数。实例方法以self 作为第一个参数。
      猜你喜欢
      • 2017-12-19
      • 2013-08-23
      • 2018-01-07
      • 2013-06-23
      • 2019-04-18
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多