2017-08-27 273 views
1

我想爲my_list的每個項目調用drawmove方法。我試過my_objects.draw()my_objects.move()而不是i.draw()i.move(),但我總是得到相同的錯誤。這裏是我的代碼:Python - Pygame AttributeError:int object has no attribute'draw'

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() 

以下是錯誤:

Traceback (most recent call last): 
    line 53, in <module> 
    number.draw() 
AttributeError: 'int' object has no attribute 'draw' 
+0

檢查壓痕請,但我看來,'當你在做range'爲'數number'創建和數量是這樣 – Y0da

回答

1

你通過索引迭代。但你真的想遍歷項目。所以你不需要range(len(...))建設。請使用for item in items。試試這個:

for rect in my_list: 
    rect.draw() 
    rect.move() 
+0

謝謝你,它的工作一個int這解釋了錯誤!這意味着我不需要範圍(len(my_list))? – Miray

+0

@Miray,對。 'range(len(my_list))'創建一個從0到9的數字範圍,''i'接收這些值。 –

+0

@Miray如果你遍歷一個'range',它給你的元素將是該範圍內的一個數字,並且數字沒有繪製方法。如果你遍歷'my_list'本身,你會得到'my_list'的每個元素,這大概確實有繪製方法。 – Carcigenicate

相關問題