Python:Object不支持索引

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

我正在尝试制作一个小弹跳游戏.我创建了这样的砖块:

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]

我试图在这里引用brickId [0]的ID:

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

早些时候,在__init__中,我将砖块定义为砖块,定义为砖块(帆布).但是,错误指出:

TypeError: 'Brick' object does not support indexing

在这个主题的其他问题的答案中,我找不到任何帮助我访问bricks.bricksId [0].

解决方法:

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

> __getitem__
> __setitem__
> __delitem__

你不需要所有这些,只需要你使用的那些.

然而,这看起来像是一个自我砖块而不是砖块列表的情况.砖块列表是可索引的;但是,除非您实施上述方法,否则不会使用砖块.

检查this以供参考.

为了能够在需要时调用self.bricks.bricksId [number]:

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

def __setitem__(self,index,value):
    self.bricks.bricksId[index] = value
上一篇:mysql没有使用索引?


下一篇:Java数组索引以某种方式超出界限?