Python: object does not support indexing

Yes, this question has been asked before. No, none of the answers I read can solve the problem that I have.

I am trying to create a little bounce game. I created such bricks:

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] 

And I'm trying to reference the bricksId[0] id here:

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

In __init__ I used to define bricks as bricks that are defined as Brick(canvas) . However, the error indicates:

 TypeError: 'Brick' object does not support indexing 

In answers to other questions on this issue, I can not find one that will help me access bricks.bricksId[0] .

+7
python object indexing typeerror
source share
1 answer

To make the Brick object iterable, you must implement methods:

 __getitem__ __setitem__ __delitem__ 

You do not need all of them, only those that you use.

However, this is similar to the case where self.bricks is a brick instead of a list of bricks. The list of bricks is indexed; however, the brick itself will not be if you do not implement the above methods.

Check this for reference.


To be able to call self.bricks.bricksId[number] when I need:

 def __getitem__(self,index): return self.bricks.bricksId[index] def __setitem__(self,index,value): self.bricks.bricksId[index] = value 
+18
source share

All Articles