有没有办法使海龟图形面向对象?
Is there a way to make turtle-graphics object oriented?
class Paddle(turtle.Turtle):
def __init__(self, pos, color, shape, speed, shape_size):
self.turtle.pos = turtle.goto(pos)
self.turtle.color = turtle.color(color)
self.turtle.shape = turtle.shape(shape)
self.turtle.speed = turtle.speed(speed)
self.turtle.shapesize = turtle.shapesize(shapesize)
OOP Python 乌龟模块
我试图通过尝试上面的代码块来使我的游戏对象面向对象,但我得到了 AttributeError: 'Paddle' object has no attribute 'turtle' traceback。老实说,我从来没有做过结合继承和模块的 OOP,所以我不太确定我应该做什么。如果您有资源让我可以了解继承如何与模块一起工作,我将不胜感激!
Python海龟图形是面向对象的。问题是,“有没有办法让你的程序面向对象?”我们可以实现您的代码以面向对象的方式尝试做的事情的精神,例如:
from turtle import Screen, Turtle
class Paddle(Turtle):
def __init__(self, position, color, shape, speed, stretch):
super().__init__(shape=shape, visible=False)
self.penup()
self.goto(position)
self.color(color)
self.shape(shape)
self.speed(speed)
self.shapesize(stretch, 1)
self.showturtle()
screen = Screen()
paddle1 = Paddle((100, 100), 'blue', 'square', 'fastest', 3)
paddle2 = Paddle((-100, 100), 'red', 'square', 'fastest', 3)
screen.exitonclick()
您混合了 isa 和 contains 的 OOP 概念。上述方案只用了isa
class Paddle(turtle.Turtle):
def __init__(self, pos, color, shape, speed, shape_size):
self.turtle.pos = turtle.goto(pos)
self.turtle.color = turtle.color(color)
self.turtle.shape = turtle.shape(shape)
self.turtle.speed = turtle.speed(speed)
self.turtle.shapesize = turtle.shapesize(shapesize)
OOP Python 乌龟模块 我试图通过尝试上面的代码块来使我的游戏对象面向对象,但我得到了 AttributeError: 'Paddle' object has no attribute 'turtle' traceback。老实说,我从来没有做过结合继承和模块的 OOP,所以我不太确定我应该做什么。如果您有资源让我可以了解继承如何与模块一起工作,我将不胜感激!
Python海龟图形是面向对象的。问题是,“有没有办法让你的程序面向对象?”我们可以实现您的代码以面向对象的方式尝试做的事情的精神,例如:
from turtle import Screen, Turtle
class Paddle(Turtle):
def __init__(self, position, color, shape, speed, stretch):
super().__init__(shape=shape, visible=False)
self.penup()
self.goto(position)
self.color(color)
self.shape(shape)
self.speed(speed)
self.shapesize(stretch, 1)
self.showturtle()
screen = Screen()
paddle1 = Paddle((100, 100), 'blue', 'square', 'fastest', 3)
paddle2 = Paddle((-100, 100), 'red', 'square', 'fastest', 3)
screen.exitonclick()
您混合了 isa 和 contains 的 OOP 概念。上述方案只用了isa