Flappy Bird开发:Paddle类实例对象不显示及属性错误问题求助
问题解决:Flappy Bird Paddle类实例不显示及属性错误
问题根源
你当前的Paddle类存在两个核心问题:
- 类内直接定义的
Paddle = turtle.Turtle()是类级别的共享海龟实例,和你创建的paddle_x对象没有关联;__init__方法仅保存了参数,并未将参数应用到这个海龟实例上,导致paddle_x无法显示。 Paddle类既没有继承turtle.Turtle,也没有将海龟实例作为自身属性,所以调用paddle_x.penup()时会提示属性不存在。
修正方案(推荐继承方式)
让Paddle类直接继承turtle.Turtle,这样实例化后的对象本身就是海龟实例,拥有所有海龟方法:
import turtle class Paddle(turtle.Turtle): def __init__(self, shape, color, stretch_wid, stretch_len, x=0, y=0): # 调用父类turtle.Turtle的初始化方法 super().__init__() self.penup() self.goto(x, y) self.shape(shape) self.color(color) self.shapesize(stretch_wid=stretch_wid, stretch_len=stretch_len) # 实例化Paddle,此时会正常显示 paddle_x = Paddle("square","white",5,5) # 你的原有paddle_a代码可以保留 paddle_a = turtle.Turtle() paddle_a.shape("square") paddle_a.color("white") paddle_a.shapesize(stretch_wid=20, stretch_len=5) paddle_a.penup() paddle_a.goto(150,-250) # 保持窗口打开 turtle.done()
另一种方案(组合方式)
如果不想继承,可将海龟实例作为Paddle类的属性:
import turtle class Paddle: def __init__(self, shape, color, stretch_wid, stretch_len, x=0, y=0): self.turtle = turtle.Turtle() self.turtle.penup() self.turtle.goto(x, y) self.turtle.shape(shape) self.turtle.color(color) self.turtle.shapesize(stretch_wid=stretch_wid, stretch_len=stretch_len) # 实例化后通过.turtle属性操作 paddle_x = Paddle("square","white",5,5) # 例如移动paddle_x:paddle_x.turtle.goto(100, 100) paddle_a = turtle.Turtle() paddle_a.shape("square") paddle_a.color("white") paddle_a.shapesize(stretch_wid=20, stretch_len=5) paddle_a.penup() paddle_a.goto(150,-250) turtle.done()
内容的提问来源于stack exchange,提问作者user69420
相关产品推荐
相关产品推荐

