是的,之前曾有人问过这个问题。不,我读过的答案都无法解决我遇到的问题。

我正在尝试创建一个小弹跳游戏。我创建了这样的积木:

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__中,我将Bricks定义为Bricks,将其定义为Brick(canvas)。但是,错误指出:
TypeError: 'Brick' object does not support indexing

在该主题的其他问题的答案中,我找不到任何可以帮助我访问bricks.bricksId[0]的内容。

最佳答案

为了使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
    

    09-25 14:56