繁体   English   中英

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

[英]How to fix “'X' object has no attribute 'y'”

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

我正在使用Turtle,对Python还是很陌生。 我为砖块设置了一个类,并且尝试为每个砖块设置一个碰撞箱。 我是通过设置取决于砖块位置的周长来实现的,因此我为碰撞盒的每一侧都设置了self.colisX变量。 但是,Atom返回一个错误,提示“ AttributeError:'Brick'对象没有属性'colisL'。”

我的积木班:

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语句注册为true,但是“ AttributeError:'Brick'对象没有属性'colisL'”不断弹出,好像该变量不存在一样。

我假设您试图制作一个使用Turtle运算的Brick类,但是覆盖self并没有您认为的那样。

正确的答案是在这种情况下使用继承 但是,如果您不熟悉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()

还要注意, Turtledistance()方法,使检查碰撞更加容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM