我试图使用OOP在Python中创建一个乌龟程序,但是我无法在另一个方法中调用一个方法。我想在设计方法中调用平方方法。
import turtle
my_turtle = turtle.Turtle()
class Circle:
def __init__(self,length,angle,speed,angle_turn):
self.length = length
self.angle = angle
self.speed = speed
self.angle_turn = angle_turn
def square(self):
for i in range(4):
my_turtle.speed(self.speed)
my_turtle.forward(self.length)
my_turtle.left(self.angle)
def design(self):
for i in range(60):
square()
my_turtle.right(self.angle_turn)
答案 0 :(得分:0)
我会这样重构您的代码
import turtle
class Circle:
def __init__(self,length,angle,speed,angle_turn):
self.length = length
self.angle = angle
self.speed = speed
self.angle_turn = angle_turn
self.my_turtle = turtle.Turtle()
def square(self):
for i in range(4):
self.my_turtle.speed(self.speed)
self.my_turtle.forward(self.length)
self.my_turtle.left(self.angle)
def design(self):
for i in range(60):
self.square()
self.my_turtle.right(self.angle_turn)
这样,您的课程就不再依赖于外部变量my_turtle。