1

I want to call the draw and move methods for each item of my_list. I tried my_objects.draw() and my_objects.move() instead of i.draw() and i.move(), but I always get the same error. Here is my code:

import pygame
import random

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)

class Rectangle():
    def __init__(self):
        self.x = random.randrange(0, 700)
        self.y = random.randrange(0, 500)
        self.height = random.randrange(20, 70)
        self.width = random.randrange(20, 70)
        self.change_x = random.randrange(-3, 3)
        self.change_y = random.randrange(-3, 3)

    def move(self):
        self.x += self.change_x
        self.y += self.change_y

    def draw(self):
        pygame.draw.rect(screen, GREEN, [self.x, self.y, self.width, self.height])

my_list = []

for number in range(10):
    my_object = Rectangle()
    my_list.append(my_object)

pygame.init()

screen = pygame.display.set_mode((700, 500))  
done = False
clock = pygame.time.Clock()

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    screen.fill(BLACK)

    for i in range(len(my_list)):
        number.draw()
        number.move()

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Here is the error:

Traceback (most recent call last):
  line 53, in <module>
  number.draw()
AttributeError: 'int' object has no attribute 'draw'
1
  • Check your indentation please but I seems that number is created when you do for number in range and this explains the error as number is an int by doing this Commented Aug 27, 2017 at 19:14

1 Answer 1

1

You're iterating through indexes. But you really want to iterate through items. So you don't need range(len(...)) construction. Instead use for item in items. Try this:

for rect in my_list:
    rect.draw()
    rect.move()
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it worked! This mean I didn't need range(len(my_list))?
@Miray If you iterate over a range, the elements it gives you will be a number in that range, and numbers don't have draw methods. If you iterate over my_list itself, you'll get each element of my_list, which presumably do have draw methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.