【发布时间】:2020-03-23 10:31:45
【问题描述】:
我有一个蛇对象,并在 draw 方法中定义了 self.rect。但是当我引用snake.rect时,它说它没有属性rect。有谁知道为什么? 蛇类:
class Snake:
def __init__(self, x, y):
self.x = x
self.y = y
self.width = 25
self.height = 25
self.direction = 1
self.kill = False
self.collide = False
def draw(self):
self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
pygame.draw.rect(screen, BLACK, self.rect)
def events(self):
# change direction on key press
self.keys = pygame.key.get_pressed()
if self.keys[pygame.K_UP]:
self.direction = 1
if self.keys[pygame.K_DOWN]:
self.direction = 3
if self.keys[pygame.K_LEFT]:
self.direction = 4
if self.keys[pygame.K_RIGHT]:
self.direction = 2
if self.rect.colliderect(food.rect):
self.collide = True
print(self.collide)
谢谢!
【问题讨论】:
-
您需要在尝试访问它之前调用
draw方法。 -
直接在init中赋值
self.rect。 -
@Dschoni,谢谢,但现在蛇不动了。任何想法为什么?
-
@Legorooj,哦,是的,我将放入 init 方法,但它现在不动。你知道为什么吗?
-
您只显示 def 代码而不是 调用 代码。这使得很难提供帮助。正如在其他 cmets 中提到的,只有在您实际调用
draw方法后才会创建该属性。在此之前尝试引用该属性会引发错误