Python:Object不支持索引

时间:2014-03-17 19:43:15

标签: python object indexing typeerror

是的,之前已经问过这个问题。不,我读过的答案都没有解决我的问题。

我试图创建一个小弹跳游戏。我已经创建了这样的砖块:

def __init__(self,canvas):
    self.canvas = canvas
    self.brick1 = canvas.create_rectangle(0,0,50,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.brick2 = canvas.create_rectangle(50,0,100,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.brick3 = canvas.create_rectangle(100,0,150,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.brick4 = canvas.create_rectangle(150,0,200,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.brick5 = canvas.create_rectangle(200,0,250,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.brick6 = canvas.create_rectangle(250,0,300,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.brick7 = canvas.create_rectangle(300,0,350,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.brick8 = canvas.create_rectangle(350,0,400,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.brick9 = canvas.create_rectangle(400,0,450,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.brick10 = canvas.create_rectangle(450,0,500,20,fill=random_fill_colour(),outline=random_fill_colour())
    self.bricksId = [self.brick1,self.brick2,self.brick3,self.brick4,self.brick5,self.brick6,self.brick7,self.brick8,self.brick9,self.brick10]

我试图在此处引用bricksId[0]的ID:

self.hit_brick(pos,self.bricks.bricksId[0])

早些时候,在__init__中,我将砖块定义为砖块,定义为Brick(canvas)。但是,错误说明:

TypeError: 'Brick' object does not support indexing

在回答此主题的其他问题时,我找不到任何帮助我访问bricks.bricksId[0]的内容。

1 个答案:

答案 0 :(得分:30)

为了使Brick对象可转换,您必须实现以下方法:

  • __getitem__
  • __setitem__
  • __delitem__

您不需要所有这些,只需要您使用的那些。

然而,这似乎是self.bricks是砖而不是砖块列表的情况。砖块列表是可索引的;但是,除非你实施上述方法,否则砖块本身并不存在。

检查this以供参考。


为了能够在我需要时致电self.bricks.bricksId[number]

def __getitem__(self,index):
    return self.bricks.bricksId[index]

def __setitem__(self,index,value):
    self.bricks.bricksId[index] = value