2012-03-16 118 views
0

这里是我的代码的故障位:蟒蛇类型错误:对象不支持索引

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')) 

的目标是与所有设置为none,但指定的专用密钥的字典。 然而,当我运行它,我得到:

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

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

回答

5

你忘了self参数newhotspot()

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

由于self将被隐式传递,无论如何,它作为args的第一个项目结束。

+0

O_O愚蠢的我...谢谢 – 2012-03-16 22:03:45

1

每一个类的方法必须采用自我,因为它是第一个参数。

试试这个:

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')) 
+0

错误,类方法把类作为第一个参数。实例方法具有“self”作为第一个参数。 – 2012-03-16 22:18:59

相关问题