Python -- Pygame 属性错误 : int object has no attribute 'draw'

标签 python python-3.x attributes pygame attributeerror

我想为 my_list 的每个项目调用 drawmove 方法。我尝试了 my_objects.draw()my_objects.move() 而不是 i.draw()i.move() ,但我总是遇到同样的错误。这是我的代码:

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'

最佳答案

您正在遍历索引。但您确实想迭代项目。所以你不需要 range(len(...)) 构造。而是使用for item in items。试试这个:

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

关于Python -- Pygame 属性错误 : int object has no attribute 'draw' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45908420/

相关文章:

python-3.x - 如何修复 Python 中的 urlopen 错误?使用 youtube-dl

variables - 在 angularjs 的 src 属性中使用 ng-repeat 变量?

python - 为什么 tarfile 模块不允许压缩 append ?

python - spyder - 清除变量资源管理器以及内存中的变量

python - 使用 Python 在 Mac 上打开 .pages 文件

python - glob 生成器的类型注释

python - 访问 job.get_output ('body' 中的流)

python-3.x - 带有覆盆子的数据矩阵

python - 项目和属性之间的区别 - Jinja,Python

c# - 有没有办法将 Controller 的 ModelState 传递(或访问)到 ActionFilterAttribute?