【问题标题】:Snake Object has no attribute 'rect'?蛇对象没有属性'rect'?
【发布时间】: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 方法后才会创建该属性。在此之前尝试引用该属性会引发错误

标签: python pygame


【解决方案1】:
class Test():
  def __init__(self, x, y):
    self.x = x
    self.y = y
    self.text = 'Hello world!'

  def another_function(self, parameter):
    self.variable = parameter

让我们看看那个简单的代码。一旦类被实例化,X 和 Y 就会被初始化,所以:

new_instance = Test(4,5)
print(new_instance.text)

会起作用。 不过

print(new_instance.variable)

将不起作用,因为variable 尚未绑定到类实例。一旦你这样做:

new_instance.another_function(3)
print(new_instance.variable)

它会起作用的。

【讨论】:

    猜你喜欢
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多