如何修复“'X' 对象没有属性 'y'”

How to fix "'X' object has no attribute 'y'"

我正在编写 Brick Breaker 代码,我为砖块设置了一个 class,我正试图为每个砖块设置一个碰撞盒。但是,无法识别这些参数供以后使用。

我正在使用 Turtle,我对 Python 还很陌生。我为砖块设置了一个 class,并试图为每个砖块设置一个碰撞盒。我通过设置一个依赖于砖块位置的周长来做到这一点,所以我为碰撞盒的每一侧设置了一个 self.colisX 变量。但是,Atom 返回错误 "AttributeError: 'Brick' object has no attribute 'colisL'."

我的积木class:

class Brick:
  def __init__(self, color, x, y):
    self = turtle.Turtle()
    self.speed(0)
    self.shape("square")
    self.color(color)
    self.penup()
    self.goto(x, y)
    self.shapesize(2.45, 2.45)
    self.x = x
    self.y = y
    self.colisL = x - 25
    self.colisR = x + 25
    self.colisU = y + 25
    self.colisD = y - 25


brick1 = Brick("purple", -175, 275)

在我的 while 循环中:

if (ball.xcor() > brick1.colisL) and (ball.xcor() < brick1.colisR) and (ball.ycor() > brick1.colisD) and (ball.ycor() < brick1.colisU):

我希望 if 语句注册为真,但 "AttributeError: 'Brick' object has no attribute 'colisL'" 一直弹出,就好像变量不存在一样。

我假设您尝试制作一个使用 Turtle 操作的 Brick class,但是重写 self 并没有按照您的想法执行。

在这种情况下,正确的答案是使用 inheritance。但是,如果您是 Python 的新手,更简单的方法是设置一个变量来包含 turtle 对象,例如:

class Brick:
  def __init__(self, color, x, y):
    self.turtle = turtle.Turtle()
    self.turtle.speed(0)
    self.turtle.shape("square")
    self.turtle.color(color)
    self.turtle.penup()
    self.turtle.goto(x, y)
    self.turtle.shapesize(2.45, 2.45)
    self.x = x
    self.y = y
    self.colisL = x - 25
    self.colisR = x + 25
    self.colisU = y + 25
    self.colisD = y - 25

可以 子类 Turtle 来专门化您的对象:

from turtle import Screen, Turtle

CURSOR_SIZE = 20
BRICK_SIZE = 50
BALL_SIZE = CURSOR_SIZE

class Brick(Turtle):
    def __init__(self, color, x, y):
        super().__init__()

        self.speed('fastest')
        self.shape('square')
        self.shapesize(BRICK_SIZE / CURSOR_SIZE)
        self.color(color)

        self.penup()
        self.goto(x, y)

brick1 = Brick('purple', -175, 275)

ball = Turtle()
ball.shape('circle')
ball.penup()
ball.goto(-160, 280)

if ball.distance(brick1) < (BALL_SIZE / 2 + BRICK_SIZE / 2):
    print("Collision!")
else:
    print("Missed!")

screen = Screen()
screen.exitonclick()

另请注意,Turtle 有一个 distance() 方法可以更轻松地检查冲突。